我失去了3天,试图弄清楚TextView
onClickListener
如何在我的代码中工作。我尝试了不同的方法,我在Stackflow中阅读了很多解决方案但似乎没有一个适合我的代码。我几乎找到了解决方案,但仍然无法正常工作。我是学生,我的导师建议我在数组上添加代码,所以我做了。
在我的应用中,我想要在TextView
点击id title_song
时,TextView
项id selecteditem
显示title_song。 title_song位于ListView中,TextView选择的是在布局中。
这是代码: -
package com.example.android.myapplication;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import static com.example.android.myapplication.R.id.selecteditem;
import static com.example.android.myapplication.R.id.title_song;
public class SongAdapter extends ArrayAdapter<Song> implements View.OnClickListener {
public SongAdapter(Context context, ArrayList<Song> pSongs) {
super(context,0, pSongs);
}
//**
// titleSong is displayed in TextView
// when item TitleSong is clicked in the ListView Song
//*
private TextView titleSong;
private TextView selectedSong;
@Override
public void onClick(View v) {
titleSong =(TextView) titleSong.findViewById(R.id.title_song);
selectedSong =(TextView) selectedSong.findViewById(R.id.selecteditem);
titleSong.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(selectedSong.getId() == R.id.title_song){
selectedSong.setText(R.id.title_song);
}
}
});
}
//**
// Provides a view for an AdapterView (ListView, GridView, etc.)
// @param position The AdapterView position that is requesting a view
// @param parent The parent ViewGroup that is used for inflation
// @return The View for the position in the AdapterView
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// Check if the existing view is being reused, otherwise inflate the view
View listItemView = convertView;
if(listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.list_item, parent, false);
}
Song local_song = getItem(position);
TextView titleTextView = (TextView) listItemView.findViewById(title_song);
titleTextView.setText(local_song.getTitleSong());
TextView artistTextView = (TextView) listItemView.findViewById(R.id.artist_song);
artistTextView.setText(local_song.getArtistSong());
return listItemView;
}
}
当然,我犯了很多错误,第一个是setText
对于我想达到的目标不正确,我知道,但它是我所知道的最相似的。 / p>
答案 0 :(得分:0)
使用这些
all = (TextView) this.findViewById(R.id.viewall);
pdf = (TextView) this.findViewById(R.id.pic);
在创建然后设置
all.setOnclickListener(this)也在oncreate()方法中。当它显示错误时,实现onClicklistener。它会像魅力一样发挥作用。
<强>被修改强>
TextView btn=(TextView) findViewById(R.id.accInfo);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//DO you work here
}
});
将Clicklistenner设置为TextView会自动使其可点击,因此无需
android:clickable="true"