在我的活动中,我有一个列表视图和一个按钮。每个都有不同的目的。
我的列表视图显示了另一项活动中的项目详细信息。
我的按钮打开另一项活动。
这里listview没有任何问题。但我的按钮不起作用。
在我的代码中,我使用了以下示例列表视图和按钮
public class MainActivity extends AppCompatActivity implements ListView.OnItemClickListener{
private Button buttonaddticket;
private ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.MainActivity );
listView = (ListView) findViewById(R.id.srListView);
listView.setOnItemClickListener(this);
buttonaddticket = (Button) findViewById(R.id.btnaddticket);
//Setting listeners to button
buttonaddticket.setOnClickListener((View.OnClickListener) this);
}
.
.
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(this, SingleTicket.class);
.
}
public void onClick(View v) {
if(v == buttonaddticket){
.
.
}
}
}
问题是如何在我的按钮的同一活动中实现onClickListener?
答案 0 :(得分:3)
您可以为Listener
Activity
public class MainActivity extends AppCompatActivity implements ListView.OnItemClickListener,View.OnClickListener{
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// handle listview on item click
}
@Override
public void onClick(View view){
switch (view.getId()){
//handle multiple view click events
}
}
}
答案 1 :(得分:0)
您需要做的是获取对按钮的引用并使用“View.OnClickListener”界面以获得要注册的单击。为了确保按钮注册了点击,它需要将其监听器设置为“this”活动。与您的按钮相比,这样您的列表就可以单独获取点击次数。
public class MainActivity extends AppCompatActivity implements ListView.OnItemClickListener, View.OnClickListener {
private Button yourButton;
private ListView listView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.MainActivity);
yourButton = (Button) findViewById(/* Your button id */);
yourButton.setOnClickListener(this);
listView = (ListView) findViewById(/* Your list id */);
listView.setOnItemClickListener(this);
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// handle listview item click here
}
@Override
public void onClick(View view){
//Handle button click here
}
}
答案 2 :(得分:0)
试试这个!!!
public class MainActivity extends AppCompatActivity implements ListView.OnItemClickListener, View.OnClickListener {
private Button buttonaddticket;
private ListView listView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.MainActivity);
buttonaddticket = (Button) findViewById(R.id.btnaddticket);
buttonaddticket.setOnClickListener(this);
listView = (ListView) findViewById(R.id.srListView);
listView.setOnItemClickListener(this);
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// handle listview item click here
}
@Override
public void onClick(View view){
switch(view.getId()){
case R.id.btnaddticket:
// Enter Code here
break;
}
}
}