У меня есть собственный Listview.in, в котором данные заполняются из массива, но я получаю повторяющееся значение в списке при заполнении списка. Пожалуйста, помогите ...
Ниже мой код
Это мой класс адаптера
public class CustomUsersAdapter extends ArrayAdapter<User>
{
public CustomUsersAdapter(Context context, ArrayList<User> users)
{
super(context, 0, users);
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
//Get an instance of our cell holder
Holder holder;
holder = new Holder();
// Get the data item for this position
User user = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null)
{
convertView = LayoutInflater.from(getContext()).inflate(R.layout.activity_main, parent, false);
// Lookup view for data population
holder.tvName = (TextView) convertView.findViewById(R.id.tvName);
holder.tvHome = (TextView) convertView.findViewById(R.id.tvHometown);
holder.tgbtn = (ToggleButton) convertView.findViewById(R.id.toggleButton1);
// Populate the data into the template view using the data object
holder.tvName.setText(user.name);
holder.tvHome.setText(user.hometown);
convertView.setTag(holder); //Add this
}
else
{
holder= (Holder) convertView.getTag();
}
/** The clicked Item in the ListView */
RelativeLayout rLayout = (RelativeLayout) convertView;
/** Getting the toggle button corresponding to the clicked item */
final ToggleButton tbtn = (ToggleButton) convertView.findViewById(R.id.toggleButton1);
tbtn.setOnClickListener(new OnClickListener() {
String homet;
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (tbtn.isChecked()) {
tbtn.setChecked(true);
ViewGroup parent = (ViewGroup) v.getParent();
TextView tvName = (TextView) parent.findViewById(R.id.tvName);
homet=tvName.getText().toString();
Toast.makeText(getContext(),homet+"Blocked", Toast.LENGTH_SHORT).show();
} else {
tbtn.setChecked(false);
Toast.makeText(getContext(),homet+ "Unblocked", Toast.LENGTH_SHORT).show();
}
}
});
// Return the completed view to render on screen
return convertView;
}
//this holder class will be filled from the layout xml and attached to the row as a tag object
private class Holder
{
TextView tvName;
TextView tvHome;
ToggleButton tgbtn,tg1;
}
}
Это мой User.java
public class User {
public String name;
public String hometown;
public static String[] call_name= {"shivni","seema","Amar","Swapna","Raj","Ayub","Reshma","Rina","Tina","Rima","Raj"};
public static String[] call_no={"987654","9876543","987654","9873455","655433","45678","56788","78899","45677","654443","5555"};
public User(String name, String hometown) {
this.name = name;
this.hometown = hometown;
}
public static ArrayList<User> getUsers() {
ArrayList<User> users = new ArrayList<User>();
for(int i=0,j=0;i<call_name.length;i++,j++)
{
users.add(new User(call_name[i], call_no[j]));
}
return users;
}
}
Это моя MainActivity
public class MainActivity extends Activity {
ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
// Attach the adapter to a ListView
listView = (ListView) findViewById(R.id.lvUsers);
populateUsersList();
}
private void populateUsersList() {
// Construct the data source
ArrayList<User> arrayOfUsers = User.getUsers();
// Create the adapter to convert the array to views
CustomUsersAdapter adapter = new CustomUsersAdapter(this, arrayOfUsers);
listView.setAdapter(adapter);
}
}
2 ответа
Я думаю, вы устанавливаете данные только при создании convertView.
holder.tvName.setText(user.name);
holder.tvHome.setText(user.hometown);
Должен вызываться не внутри блока if (convertView == null)
, а всегда выполняться. Так что поместите его за блоком else.
Переместите этот фрагмент кода:
// Populate the data into the template view using the data object
holder.tvName.setText(user.name);
holder.tvHome.setText(user.hometown);
Переместите его, как показано ниже:
// Populate the data into the template view using the data object
holder.tvName.setText(user.name);
holder.tvHome.setText(user.hometown);
/** The clicked Item in the ListView */
RelativeLayout rLayout = (RelativeLayout) convertView;
Похожие вопросы
Новые вопросы
android
Android — это мобильная операционная система Google, используемая для программирования или разработки цифровых устройств (смартфонов, планшетов, автомобилей, телевизоров, одежды, очков, IoT). Для тем, связанных с Android, используйте теги, специфичные для Android, такие как android-intent, android-activity, android-adapter и т. д. Для вопросов, отличных от разработки или программирования, но связанных с Android framework, используйте эту ссылку: https://android .stackexchange.com.