Dynamic buttons dont show in android studio using fragments - java

Im trying to dynamicaly add buttons to a fragment, but they do not show.
This is the listCharacter.java:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_list_character, container, false);
context = view.getContext();
for (int i = 1; i <= 20; i++) {
LinearLayout layout = new LinearLayout(context);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
Button firstBtn = new Button(this.context);
firstBtn.setId(i);
final int id_ = firstBtn.getId();
/**
* The text is not updated(?)
*/
firstBtn.setText("button " + id_);
/**
* it does not add 20 button, might be on top of each other
*/
layout.addView(firstBtn, params);
firstBtn = view.findViewById(R.id.characterNameBtn);
firstBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Toast.makeText(view.getContext(),
"Button clicked index = " + id_, Toast.LENGTH_SHORT)
.show();
Navigation.findNavController(view).navigate(R.id.action_listCharacter_to_loadCharacter);
}
});
}
return view;
}
And this is the fragment_list_character.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/frameLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/background"
tools:context=".listCharacter"
android:orientation="vertical">
<LinearLayout
android:id="#+id/list_character_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp">
<Button
android:id="#+id/characterNameBtn"
android:layout_width="match_parent"
android:layout_height="70dp"
android:background="#66000000"
android:fontFamily="#font/main"
android:gravity="center"
android:padding="5dp"
android:text=""
android:textColor="#fff"
android:textSize="40sp"
/>
</LinearLayout>
</LinearLayout>
I dont get any error messages atm, but i cant see the buttons when i run the program.
The on click works and it says it has id 20.

You're adding the buttons to a LinearLayout that you are recreating each time through your loop.
for (int i = 1; i <= 20; i++) {
LinearLayout layout = new LinearLayout(context);
...
layout.addView(firstBtn, params)
....
}
layout is never added to the view that is returned. You will need to add the buttons to the view or to a child of the view that you return to see them on the screen. I think that there are a few other issues, but this would be the first one to address.

Related

Set a title and description for each photo in carouse android

I am using a carouselView library for my app. https://github.com/sayyam/carouselview
The images are displaying and the carousel is working but how do I set a title and description below each image as it slides for each image.
I have a string containing all the title and text for each image.
e.g
<string name="first_image_title">First image title</string>
<string name="first_image_desc">This is a description for first image title</string>
<string name="second_image_title">2nd image title</string>
<string name="second_image_desc">This is a description for the second image title</string>
<string name="third_image_title">3rd image title</string>
<string name="third_image_desc">This is a description for the third image title</string>
All these are supposed to be placed below the sliding images (for each image.)
fragment_safety.xml
Containing the image and where the title and description for each image supposed to be
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context="fragments.SafetyFragment">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tabContent"
android:background="#drawable/rounded_corner2">
<com.synnapps.carouselview.CarouselView
android:id="#+id/carouselView"
android:layout_width="match_parent"
android:layout_height="200dp"
app:fillColor="#FFFFFFFF"
app:pageColor="#00000000"
app:radius="6dp"
app:slideInterval="5000"
app:strokeColor="#FF777777"
app:strokeWidth="1dp"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/textTitle"
android:layout_below="#+id/carouselView"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/textDesc"
android:layout_below="#+id/textTitle"/>
</RelativLayout>
SafetyFragment.java
According to the doc, I am supposed to implement ViewListener for customView but I cant wrap my head around how to do this....Get all the titles and description in the string and set them for each of the images sliding.
public class SafetyFragment extends Fragment {
private CarouselView carouselView;
private int[] sampleImages = {R.drawable.image1,
R.drawable.image2, R.drawable.image3,
R.drawable.image4, R.drawable.image5,
R.drawable.image6};
public SafetyFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View root = inflater.inflate(R.layout.fragment_safety, container, false);
carouselView = root.findViewById(R.id.carouselView);
ImageListener imagesListenerx = new ImageListener() {
#Override
public void setImageForPosition(int position, ImageView imageView) {
Glide.with(SafetyFragment.this).load(sampleImages[position]).into(imageView);
}
};
ViewListener viewListener = new ViewListener() {
#Override
public View setViewForPosition(int position) {
View customView = getLayoutInflater().inflate(R.layout.fragment_safety, null);
//set view attributes here
return customView;
}
};
carouselView.setPageCount(sampleImages.length);
carouselView.setViewListener(viewListener);
return root;
}
}
I found a way to do this.
1.Declare a string array for each text you want to display in each carousel
private String[] titles = {"One", "Two", "Three"}
2. Set a custom view listener and get the view in the layout
ViewListener viewListener = new ViewListener() {
int i;
#Override
public View setViewForPosition(int position) {
View customView = getLayoutInflater().inflate(R.layout.fragment_safety, null);
//set view attributes here
safety_title = customView.findViewById(R.id.safetyTextTitle);
safety_images = customView.findViewById(R.id.safetyImages);
Glide.with(SafetyFragment.this).load(sampleImages[position]).into(safety_images);
//Very Important
safety_title.setText(titles[position]);
return customView;
}
};
As per the documentation you can create a custom view and bind views with the data
ViewListener viewListener = new ViewListener() {
#Override
public View setViewForPosition(int position) {
View customView = getLayoutInflater().inflate(R.layout.view_custom, null);
//set view attributes here
return customView;
}
};
I use this way:
ViewListener viewListener = new ViewListener() {
#Override
public View setViewForPosition(int position) {
View customView = getLayoutInflater().inflate(R.layout.custom_carousel, null);
//set view attributes here
TextView car_title = (TextView) customView.findViewById(R.id.textTitle);
ImageView car_image = (ImageView) customView.findViewById(R.id.imageView);
car_title.setText(sampleTitle[position]);
car_image.setImageResource(sampleImages[position]);
return customView;
}
};
While custom view in custom_carousel.xml will be like this:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<ImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/textDesc"
android:layout_marginStart="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
tools:src="#tools:sample/avatars[1]" />
<TextView
android:id="#+id/textTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginEnd="8dp"
android:text="test" />
</RelativeLayout>

How to make discrete seek/progress bar in android?

How to make discrete progress/seek bar like stepper in android. Like we see in whatsapp status stories.
Although it is implemented by so many libraries out there, but i need to implement it without using libraries.
I use views in horizontal linear layout and divide it dynamically based on number of sections or number of status stories need to be shown.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
tools:context=".MainActivity">
<LinearLayout
android:id="#+id/layout_views"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:orientation="horizontal"
android:padding="4dp" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:text="Click" />
</LinearLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
String TAG = "MainActivity";
Button mButton;
int x=0,height,width,numberOfSections;
LinearLayout layoutViews;
ArrayList<View> viewsList =new ArrayList<>();
#SuppressLint("ClickableViewAccessibility")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//findviews
layoutViews = findViewById(R.id.layout_views);
mButton = (Button) findViewById(R.id.button);
//for getting dimensions of screen
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
height = displayMetrics.heightPixels;
width = displayMetrics.widthPixels;
//suppose we have to cut section into 4 parts
numberOfSections = 10;
width -= (16 + 16*numberOfSections); //reducing length of layout by 16dp from left and right and in between 16dp {in between*number of sections)
width /= numberOfSections;
for(int i=0;i<numberOfSections;i++){
View v = new View(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width, 10);
params.setMargins(16,0,0,0); //giving 16dp internal margin between two views
v.setLayoutParams(params);
viewsList.add(v); //adding views in array list for changing color on click of button
v.setBackgroundColor(getResources().getColor(colorAccent));
layoutViews.addView(v);
}
//button onclick function
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
buttonClick();
}
});
}
public void buttonClick(){
viewsList.get(x).setBackgroundColor(getResources().getColor(colorPrimaryDark));
x++;
}
}
Voyella! You have made this dynamic story progress bar, although you can add transition animation in views.

I can't set the button width inside the table view

I'm doing an android application where I have to dynamically put a button inside the table row. The problem is that the button that I create is stretched as in the image below:
I also put some of the application code here below so you can understand better.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_punteggio);
showAlertDialog_modality(R.layout.dialog_change_modality);
final TableLayout tableLayout = findViewById(R.id.tableLayout);
final RelativeLayout relativeLayout = findViewById(R.id.relativeLayout);
final Button btn_settings = findViewById(R.id.btn_settings);
Bundle datipassati = getIntent().getExtras();
String player = datipassati.getString("players");
giocatore = player.split("%");
Log.d("TAG", "array: " + giocatore[0]);
for (int i = 0; i < giocatore.length; i++) {
punti[i] = 0;
TableRow tbrow = new TableRow(this);
final TextView t3v = new TextView(this);
txPunti[i] = t3v;
//------------------------- Textview Player
final TextView t1v = new TextView(this);
t1v.setText(giocatore[i].toUpperCase());
t1v.setTextColor(Color.BLACK);
t1v.setGravity(Gravity.CENTER);
t1v.setTextSize(20);
t1v.setWidth(400);
tbrow.addView(t1v);
//-------------------- BTN MENO
Button btnMeno = new Button(this);
btnMeno.setText("-");
btnMeno.setTextColor(Color.BLACK);
btnMeno.setGravity(Gravity.CENTER);
tbrow.addView(btnMeno);
btnMeno.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
removepoint(t3v);
}
});
// --------------------- TEXT VIEW PUNTI
t3v.setText(punti[i]+"");
t3v.setTextSize(25);
t3v.setMaxWidth(150);
t3v.setPadding(20,0,20,0);
t3v.setTypeface(t3v.getTypeface(), Typeface.BOLD);
t3v.setTextColor(Color.RED);
t3v.setGravity(Gravity.CENTER);
tbrow.addView(t3v);
//----------------------------- BTN PIU
Button btnPiu = new Button(this);
btnPiu.setBackground(ContextCompat.getDrawable(Activity_punteggio.this, R.drawable.ic_add_circle_black_24dp));
btnPiu.setTextColor(Color.BLACK);
btnPiu.setGravity(Gravity.CENTER);
tbrow.addView(btnPiu);
btnPiu.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
addPoint(t3v, t1v);
}
});
tableLayout.addView(tbrow);
}
btn_settings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showAlertDialog_modality(R.layout.dialog_change_modality);
}
});
}
Here's also the xml file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Activity_punteggio">
<Button
android:id="#+id/btn_settings"
android:layout_width="55dp"
android:layout_height="32dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="0dp"
android:layout_marginRight="1dp"
android:background="#android:color/transparent"
android:drawableBottom="#drawable/ic_settings_black_24dp" />
<TextView
android:id="#+id/title_player"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:text="Chip-Chop"
android:textSize="25dp"
android:textStyle="bold|italic" />
<TableLayout
android:id="#+id/tableLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="80dp">
</TableLayout>
</RelativeLayout>
I hope you could help me.
Please check this solution. setImageResource is the method assign
image resource. Set background method is recommended for the
background of the button.
ImageButton btnPiu = new ImageButton(this);
btnPiu.setImageDrawable(ContextCompat.getDrawable(Activity_punteggio.this, R.drawable.ic_add_circle_black_24dp));
btnPiu.setTextColor(Color.BLACK);
btnPiu.setGravity(Gravity.CENTER);
tbrow.addView(btnPiu);
btnPiu.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
addPoint(t3v, t1v);
}
});
tableLayout.addView(tbrow);
I used ImageButton other than Button.
setImageDrawable
try to edit android:layout_height="32dp" to android:layout_height="55dp"
android:id="#+id/btn_settings"
android:layout_width="55dp"
android:layout_height="55dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="0dp"
android:layout_marginRight="1dp"
android:background="#android:color/transparent"
android:drawableBottom="#drawable/ic_settings_black_24dp" />
I hope it will work with you .
THIS is make very complex coding, Make it simpler.Don't create whole row dynamically in FOR loop. Instead of that
First Create Separate XML for that row.
Write Below code and your row append into tablelayout.
for (int i = 0; i < giocatore.length; i++) {
View trView = LayoutInflater.from(getActivity()).inflate(R.layout.xmlID,null);
TextView lblGuestName;
lblGuestName = trView.findViewById(R.id.lbl);
lblGuestName.setText("Guest 1");
tableLayout.addView(trView);
}
This Way you easily configure any complex row in tablelayout. No need to make it dynamically.
Feel free to reply.

Add buttons dynamically to ScrollView android

So I want to add x amount of buttons to a layout in android (where x is usually between 4 and 24), and I can achieve this using the code below, but it doesn't scroll so it cuts off some of the buttons
I am using a fragment, which contains a LinearLayout and BottomNavigation, and one of those navigation options leads to the fragment contained below
At the moment my.xml file looks like:
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/units_group"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
android:layout_marginEnd="20dp"
android:layout_marginStart="20dp"
android:layout_marginTop="20dp"
android:orientation="vertical">
</LinearLayout>
</ScrollView>
And my code:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_course_units, container, false);
final LinearLayout unitsBtns = (LinearLayout) view.findViewById(R.id.units_group);
//I actually get this from a volley request but didn't want to include all the code
String[] units = {"1", "2", "3", "4", "5", "6", "7", "8"};
for(int i = 0; i < units.length; i++){
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
);
params.setMargins(0, 30, 0, 0);
Button b = new Button(getActivity());
b.setLayoutParams(params);
b.setText(units[i]);
b.setId(i);
b.setBackgroundColor(Color.WHITE);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
// STUFF HERE
} catch (Exception e) {
e.printStackTrace();
}
}
});
unitsBtns.addView(b);
}
return view;
}
Is there any way to get the buttons to be scrollable? I have tried to put the scrollView around the parent of this too and it still doesn't seem to work.
Note: I am still pretty new to developing native Android apps so please correct me if I'm doing something incorrectly
when you have to use ScrollView you should give android:layout_height="wrap_content" in child view of ScrollView then only you have to scroll your view
You should use user LinearLayout like this
<LinearLayout
android:id="#+id/units_group"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginEnd="20dp"
android:layout_marginStart="20dp"
android:layout_marginTop="20dp"
android:orientation="vertical">
</LinearLayout>
here also you have to replace
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
Note: when you give match_parent in height attribute, it will limit your view to device screen
hope it will help you.. :)
Here's a working example (horizontal) :
<HorizontalScrollView
android:id="#+id/hsv1"
android:scrollbars="none"
android:background="#0d47a1"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:id="#+id/hsvLayout1"
android:background="#0d47a1"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</LinearLayout>
</HorizontalScrollView>
Get ScrollView and Layout:
HorizontalScrollView hsv1 = (HorizontalScrollView) findViewById( R.id.hsv1 );
LinearLayout layout = (LinearLayout) hsv1.findViewById( R.id.hsvLayout1 );
layout.removeAllViews();
Create a button dynamically:
Button myButton = new Button (this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT );
lp.setMargins( 20, 0, 20, 0 );
myButton.setLayoutParams(lp);
myButton.setTextColor( Color.YELLOW );
myButton.setGravity( Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL );
myButton.setText( "Hello World !" );
Add button to layout:
layout.addView(myButton);

Create a ListView with selectable rows/change background color of ListView rows when clicked

Problem
I'm trying to create a ListView with selectable items. I want to be able to click on an item in the ListView and have the item change color in the list, and then go on and do something else with the data from the row.
I'm using a SimpleAdapter.
How do I make it so that when I tap on a row, it turns a different color, and then when I tap on a different row, the new row is selected and changed to a new color, and the old row changes back to normal?
Code
Here is my code so far. The DBTools class is has all of the data that I want to be displayed in my ListView organized and taken care of. The getAllReceivers() method returns an ArrayList of HashMap<String, String>s that have all of my data.
MainActivity.java:
public class MainActivity extends ListActivity {
DBTools dbTools = new DBTools(this);
ArrayList<HashMap<String, String>> receiverList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActionBar().hide();
setContentView(R.layout.activity_main);
receiverList = dbTools.getAllReceivers();
dbTools.close();
ListView listView = getListView();
if(receiverList.size() != 0) {
SimpleAdapter adapter = new SimpleAdapter(MainActivity.this,receiverList, R.layout.receiver_entry, new String[] {"receiverId","receiverName", "fullPath"}, new int[] {R.id.receiverId, R.id.receiverName, R.id.fullPath});
setListAdapter(adapter);
}
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/black" >
<TextView
android:id="#+id/titleTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="My List" />
</TableRow>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/black"
android:id="#android:id/list" />
</TableLayout>
receiver_entry.xml
<?xml version="1.0" encoding="utf-8"?>
<TableRow xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/tableRow" >
<TextView
android:id="#+id/receiverId"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:visibility="gone" />
<TextView
android:id="#+id/receiverName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Robotronics" />
<TextView
android:id="#+id/fullPath"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="123.45.678.910:8088/robtrox/find" />
</TableRow>
Solution
The solution to this problem is very simple. We need to add an OnItemClickListener to our ListView to listen for clicks and respond accordingly.
So, in the onCreate() method, once you've made sure that you set of data isn't empty, you're going to want to Override the onItemClick() method to listen for the click and change the color. You're also going to want to keep track of which item you selected for the later steps, so add public int selectionId = -1; at the top of your class. Furthermore, you'll need to let the ListAdapter know that you changed something by calling ((SimpleAdapter) getListAdapter()).notifyDataSetChanged().
if(receiverList.size() != 0) {
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int index, long id) {
view.setBackgroundColor(Color.RED);
TextView receiverIdTextView = (TextView) view.findViewById(R.id.receiverId);
selectionId = Integer.valueOf(receiverIdTextView.getText().toString());
((SimpleAdapter) getListAdapter()).notifyDataSetChanged();
}
});
SimpleAdapter adapter = getNewAdapter();
setListAdapter(adapter);
}
Great! Now we have a working system that will change the color of the row that you tap. But we're not done yet. We need to make sure that the previous selection changes back to the normal color.
For this, we are going to use override the SimpleAdapter's getView() method, which is called everytime the ListView goes to draw the items being displayed in it.
It only actually displays the items it needs to - the ones that you can see. It does not render the ones above or below your screen. So if you have 200 items in a ListView, only 5 or 6, depending on the size of your screen and the size of the items, are being rendered at a time.
To override the getView() method, go up to where you initialize the adapter and change the code to this:
SimpleAdapter adapter = new SimpleAdapter(MainActivity.this,receiverList, R.layout.receiver_entry, new String[] { "receiverId","receiverName", "fullPath"}, new int[] {R.id.receiverId, R.id.receiverName, R.id.fullPath}) {
#Override
public View getView (int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
TextView receiverIdTextView = (TextView) view.findViewById(R.id.receiverId);
if(receiverIdTextView.getText().toString().equals(String.valueOf(selectionId))) {
view.setBackgroundColor(Color.RED);
} else {
view.setBackgroundColor(Color.WHITE);
}
return view;
}
};
Every time one of the rows is drawn, since the getView() will get called, the ListView will check if the current view has the id of row you selected. If it doesn't, it'll change the background color to white. If it does, it'll change the background color to red.
And voila! That's it! Now you are setting the background color to red when you click on an item in the ListView.
Final Code
MainActivity.java:
public class MainActivity extends ListActivity {
DBTools dbTools = new DBTools(this);
ArrayList<HashMap<String, String>> receiverList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActionBar().hide();
setContentView(R.layout.activity_main);
receiverList = dbTools.getAllReceivers();
dbTools.close();
ListView listView = getListView();
if(receiverList.size() != 0) {
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int index, long id) {
view.setBackgroundColor(Color.RED);
TextView receiverIdTextView = (TextView) view.findViewById(R.id.receiverId);
selectionId = Integer.valueOf(receiverIdTextView.getText().toString());
((SimpleAdapter) getListAdapter()).notifyDataSetChanged();
}
});
SimpleAdapter adapter = new SimpleAdapter(MainActivity.this,receiverList, R.layout.receiver_entry, new String[] { "receiverId","receiverName", "fullPath"}, new int[] {R.id.receiverId, R.id.receiverName, R.id.fullPath}) {
#Override
public View getView (int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
TextView receiverIdTextView = (TextView) view.findViewById(R.id.receiverId);
if(receiverIdTextView.getText().toString().equals(String.valueOf(selectionId))) {
view.setBackgroundColor(Color.RED);
} else {
view.setBackgroundColor(Color.WHITE);
}
return view;
}
};
setListAdapter(adapter);
}
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/black" >
<TextView
android:id="#+id/titleTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="My List" />
</TableRow>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/black"
android:id="#android:id/list" />
</TableLayout>
receiver_entry.xml
<?xml version="1.0" encoding="utf-8"?>
<TableRow xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/tableRow" >
<TextView
android:id="#+id/receiverId"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:visibility="gone" />
<TextView
android:id="#+id/receiverName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Robotronics" />
<TextView
android:id="#+id/fullPath"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="123.45.678.910:8088/robtrox/find" />
</TableRow>

Categories