如何使用户可以在点击监听器上设置多个按钮。我尝试了2个按钮,但是它说我已经定义了点击式监听器,因此我无法在点击监听器上创建另一个。我到目前为止的代码是:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.LinearLayout;
public class MainActivity extends AppCompatActivity {
private View btnRender;
private LinearLayout container;
private View btnRendered;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnRender = (View)findViewById(R.id.btn_render);
container = (LinearLayout)findViewById(R.id.fragment_layout);
btnRendered = (View) findViewById(R.id.btn_rendered);
//set event handling for button
btnRender.setOnClickListener(onClickListener());
}
private View.OnClickListener onClickListener() {
return new View.OnClickListener() {
@Override
public void onClick(View v) {
//replace fragment when clicked
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.fragment_layout, new PDFRenderFragment());
ft.commit();
//gone button after all
btnRender.setVisibility(View.GONE);
container.setVisibility(View.VISIBLE);
}
};
}
}
btn_rendered
是我要设置点击监听器的另一个按钮,但软件不允许我这样做。我是否需要设置一个switch-case方法才能工作?
我刚尝试了两个代码,但似乎都没有达到预期的效果。现在每当我点击其中一个按钮时,第二个pdf总会显示! (我使用的按钮是什么)
答案 0 :(得分:1)
你可以像下面这样处理。
btnRender.setOnClickListener(onClickListener());
btnRendered.setOnClickListener(onClickListener());
private View.OnClickListener onClickListener() {
return new View.OnClickListener() {
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.btn_render:
//replace fragment when clicked
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.fragment_layout, new PDFRenderFragment());
ft.commit();
//gone button after all
btnRender.setVisibility(View.GONE);
container.setVisibility(View.VISIBLE);
break;
case R.id.btn_rendered:
// your logic here
break;
}
}
};
}
答案 1 :(得分:0)
您也可以对第二个按钮使用相同的方法,并使用if / else条件来识别在该方法中单击哪个按钮。 如下面的代码。
//set event handling for button
btnRender.setOnClickListener(onClickListener());
second_btn.setOnClickListener(onClickListener());
您的 onClickListener 方法。
private View.OnClickListener onClickListener() {
return new View.OnClickListener() {
@Override
public void onClick(View v) {
//replace fragment when clicked
if (v == btnRender) {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.fragment_layout, new PDFRenderFragment());
ft.commit();
//gone button after all
btnRender.setVisibility(View.GONE);
container.setVisibility(View.VISIBLE);
} else if (v == second_btn) {
//second button click code
}
}
};
}