Struggling to replace SPINNER with BUTTONS populated from database - android

Trying to replace spinner with buttons dynamically populated from database.
Normally spinner use array adapter and built-in List Item Layouts "android.R.layout.simple_spinner_item"etc.
How should it be modified if instead of spinner you want to populate buttons?
Should I replace layouts for spinner in my in loadDifficulties() method with layouts for buttons?
HERE HOW IT WORKED WITH SPINNER
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_starting_screen);
spinnerDifficulty = findViewById(R.id.spinner_quizlist);
loadDifficulties();
Button startTest = findViewById(R.id.start_test);
startTest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startQuiz();
}
});
}
private void startQuiz() {
ListQuiz selectedLevel = (ListQuiz) spinnerDifficulty.getSelectedItem();
int LevelListID = selectedLevel.getId();
String quizListName = selectedLevel.getName();
Intent intent = new Intent(StartingScreenActivity.this, MainActivity.class);
intent.putExtra(EXTRA_DIFFICULTY_ID, LevelListID);
intent.putExtra(EXTRA_DIFFICULTY_NAME, quizListName);
startActivityForResult(intent, REQUEST_CODE_QUIZ);
}
private void loadDifficulties(){
QuizDbHelper dbHelper = QuizDbHelper.getInstance(this);
List<ListQuiz> LevelList = dbHelper.getAllListQuiz();
ArrayAdapter<ListQuiz> adapterLevelList = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, LevelList); adapterLevelList.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerDifficulty.setAdapter(adapterLevelList);
}

onCreate(){
LinearLayout listOrders = findViewById(R.id.listOrders);
for (int i = 0; i < listForShowing.size(); i++){
String text = listForShowing.get(i);
listOrders.addView(createButton(text));
}
listOrders.requestLayout();
}
public Button createButton(String text){
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Button button = inflater.inflate(R.layout.button, null);
button.setText(text);
}

Briefly
Created LinearLayout for buttons.
I didn't need to use ArrayAdapter in the loadDifficulties anymore.
Added all needed parameters to startQuiz() (in my case int & String) simplifying method to Intents only.
private ArrayAdapter <ListQuiz> adapter;
private Button autobutton;
public int categorySize;
private List<ListQuiz> categoryName;
private LinearLayout QuizListLayout;
private Button levelButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_starting_screen);
autobutton = findViewById(R.id.autobutton);
loadDifficulties();
QuizListLayout = findViewById(R.id.layoutForButtons);
for(int i=0; i<categorySize;i++){
levelButton =new Button(this);
levelButton.setText("" + categoryName.get(i));
levelButton.setId(i);
final int index = i;
levelButton.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
levelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startQuiz(v.getId(), categoryName.get(index).toString());
}
});
QuizListLayout.addView(levelButton);
}
}
private void startQuiz(int LevelListID, String quizListName) {
Intent intent = new Intent(StartingScreenActivity.this, MainActivity.class);
intent.putExtra(EXTRA_DIFFICULTY_ID, LevelListID);
intent.putExtra(EXTRA_DIFFICULTY_NAME, quizListName);
startActivityForResult(intent, REQUEST_CODE_QUIZ);
}
private void loadDifficulties(){
QuizDbHelper dbHelper = QuizDbHelper.getInstance(this);
List<ListQuiz> LevelList = dbHelper.getAllListQuiz();
categorySize = dbHelper.getAllListQuiz().size();
categoryName = dbHelper.getAllListQuiz();
buttonlayout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="#+id/layoutForButtons">
</LinearLayout>

Related

Updating filtered listview with a custom adapter

I'm creating a music player. This class among other things is suppose to add new songs to the playlist.
A new window pops up with available songs and the checked songs get added. Songs can be filtered and the selected rows are to change the color when the checkbox is checked. The filtering works and everything is being added the way it's suppose to but...
The problem is that when I check a song/some songs and then click on the search filter and the soft keyboard pops up the color of the selected rows changes to the default color, (the the song is still checked and can be added to the Playlist). When songs are checked and I hide the keyboard the same thing happens.
The other issue is that when the list gets filtered the color of the row previously selected goes away as well when the search box is cleared, the songs remain schecked though.
And I don't understand how and why that happens and therefore how to fix this.
Anyone has any ideas, please?
I think I don't understand how updating after filtering works and what notifyDataSetChanged() does exactly.
Here's the adapter code :
public class MyTrackAdapter extends ArrayAdapter<File>
{
private final Activity context;
private ArrayList<File> album, temp;
private ArrayList<File> piosenki;
public MyTrackAdapter(Activity context, ArrayList<File> album)
{
super(context, R.layout.adapter_traki, album);
this.context = context;
this.temp = new ArrayList<File>(album);
this.album = album;
this.piosenki=new ArrayList<File>();
}
public View getView(int position, View view, ViewGroup parent)
{
LayoutInflater inflater = context.getLayoutInflater();
final View rowView = inflater.inflate(R.layout.adapter_traki, null,true);
final CheckBox cb_plus = (CheckBox) rowView.findViewById(R.id.add);
final int position1=position;
final TextView txt = (TextView) rowView.findViewById(R.id.list_text);
if(position1 %2 == 1) rowView.setBackgroundResource(R.color.bbcolor);
else rowView.setBackgroundResource(R.color.bpcolor);
txt.setText(album.get(position1).getName().toString().replace(".mp3",""));
cb_plus.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
if (cb_plus.isChecked())
{
cb_plus.setBackgroundResource(R.drawable.x2);
txt.setTextColor(context.getResources().getColor(R.color.bdcolor));
rowView.setBackgroundResource(R.color.acolor);
piosenki.add(album.get(position1));
}
else
{
cb_plus.setBackgroundResource(R.drawable.plus);
txt.setTextColor(context.getResources().getColor(R.color.gcolor));
if(position1 %2 == 1) rowView.setBackgroundResource(R.color.bbcolor);
else rowView.setBackgroundResource(R.color.bpcolor);
piosenki.remove(album.get(position1));
}
}
});
return rowView;
}
public void showTost(String s)
{
Toast.makeText(context, s, Toast.LENGTH_SHORT).show();
}
public ArrayList<File> getpiosenki()
{
return piosenki;
}
public Filter getFilter()
{
return filtr;
}
private Filter filtr = new Filter()
{
protected FilterResults performFiltering(CharSequence s)
{
FilterResults r = new FilterResults();
ArrayList<File> f = new ArrayList<File>();
if(s==null || s.length()==0) f.addAll(temp);
else
{
String ss=s.toString().toLowerCase().trim();
for(File ff : temp) if(ff.getName().replace(".mp3", "").toLowerCase().contains(ss)) f.add(ff);
}
r.values=f;
r.count=f.size();
return r;
}
protected void publishResults(CharSequence s, FilterResults r)
{
album.clear();
album.addAll((ArrayList)r.values);
notifyDataSetChanged();
}
};
}
And the Playlist class :
public class Playlist extends Activity implements TextWatcher
{
int where;
long pos;
String pllist;
ArrayList<String> lstp, lsts;
ArrayList<Long> lsti;
ArrayList<Integer> lstx;
DBHandler db;
private TextView txt1, txt2;
ImageView pic;
private ListView lv_traki;
ListView lv_traki2add;
PopupWindow pw;
View popupv;
TextView etext;
MyTrackAdapter tadapter;
ImageView add2list;
ArrayList <File> piosenki, toadd;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.playlist);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
db = new DBHandler(getApplicationContext());
Intent tnt = getIntent();
Bundle bn = tnt.getExtras();
lstp = (ArrayList) bn.getParcelableArrayList("path");
lsts = (ArrayList) bn.getParcelableArrayList("song");
lsti = (ArrayList) bn.getParcelableArrayList("indx");
lstx = (ArrayList) bn.getParcelableArrayList("pause");
pos = bn.getLong("pos", 0);
where = bn.getInt("skad", 0);
pllist = bn.getString("album");
piosenki = (ArrayList) bn.getParcelableArrayList("full");
setData(0, lstp.size());
songlist();
lv_traki.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> adapterView, View v, int i, long l)
{
Intent it;
lstp.clear();
lsti.clear();
lsts.clear();
lstx.clear();
db.gett1path(pos, lstp);
db.gett1song(pos, lsts);
db.gett1pause(pos, lstx);
db.gett1id(pos, lsti);
it=new Intent(getApplicationContext(), Player.class);
it.putExtra("path", lstp).putExtra("nazwa", lsts).putExtra("pause", lstx).putExtra("pos",i).putExtra("skad",4);
startActivity(it);
}
});
if(where==5) lv_traki.performItemClick(lv_traki.getAdapter().getView(0, null, null), 0, lv_traki.getAdapter().getItemId(0));
add2list = (ImageView) findViewById(R.id.btn_addtoplay);
toadd = new ArrayList<File>();
add2list.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
popupv = ((LayoutInflater) getApplicationContext().getSystemService("layout_inflater")).inflate(R.layout.popup_addtolist, null);
ImageView btn01 = (ImageView) popupv.findViewById(R.id.btn_addtoplay);
FrameLayout fl = (FrameLayout) findViewById(R.id.frameLayout1);
etext = (EditText) popupv.findViewById(R.id.etext);
etext.addTextChangedListener(Playlist.this);
lv_traki2add = (ListView) popupv.findViewById(R.id.lst_traki2add);
tadapter = new MyTrackAdapter(Playlist.this, piosenki);
lv_traki2add.setAdapter(tadapter);
toadd=tadapter.getpiosenki();
btn01.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
if(toadd.size()>0)
{
for (File addt1 : toadd)
{
db.addt1(pos, addt1);
}
lstp.clear();
lsts.clear();
lstx.clear();
lsti.clear();
db.gett1path(pos, lstp);
db.gett1song(pos, lsts);
db.gett1pause(pos, lstx);
db.gett1id(pos, lsti);
lv_traki.setAdapter(null);
setData(0, lstp.size());
MyPlaylistAdapter adapter=new MyPlaylistAdapter(Playlist.this, lsts, lstp, lsti, lstx, pos, pllist, lv_traki, txt2);
lv_traki.setAdapter(adapter);
for(int x=0; x<lv_traki2add.getChildCount(); x++)
{
CheckBox cb = lv_traki2add.getChildAt(x).findViewById(R.id.add);
cb.setChecked(false);
}
pw.dismiss();
showTost("Songs Added");
}
else pw.dismiss();
}
});
pw = new PopupWindow(popupv, -1, -1, true);
pw.showAtLocation(fl, 17, 0, 0);
}
});
}
private void songlist()
{
lv_traki = (ListView) findViewById(R.id.lst_traki);
MyPlaylistAdapter adapter=new MyPlaylistAdapter(this, lsts, lstp, lsti, lstx, pos, pllist, lv_traki, txt2);
lv_traki.setAdapter(adapter);
}
public void setData(int z, int size)
{
MediaMetadataRetriever mmr = new MediaMetadataRetriever();
MediaMetadataRetriever tmp = new MediaMetadataRetriever();
mmr.setDataSource(lstp.get(z));
txt1 = (TextView) findViewById(R.id.txt1);
txt2 = (TextView) findViewById(R.id.txt2);
pic = (ImageView) findViewById(R.id.img_bg);
int tmax = 0;
for(int i=0;i<size;i++)
{
tmp.setDataSource(lstp.get(i));
tmax+=Integer.parseInt(tmp.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION));
tmax+=lstx.get(i)*1000;
}
txt1.setText(pllist);
if (size>1) txt2.setText(size+" songs; "+mili_t(tmax));
else txt2.setText("1 song; "+mili_t(tmax));
Bitmap bm;
Drawable d;
byte [] img = mmr.getEmbeddedPicture();
if(img!=null)
{
bm = BitmapFactory.decodeByteArray(img, 0, img.length);
d = new BitmapDrawable(getResources(), bm);
pic.setBackground(d);
}
else
{
pic.setBackgroundResource(R.drawable.no_image);
pic.getLayoutParams().height = 400;
pic.getLayoutParams().width = 400;
pic.setScaleType(ScaleType.CENTER_INSIDE);
}
}
public String mili_t(int t)
{
int s = (int) (t / 1000) % 60 ;
int m = (int) ((t / (1000*60)) % 60);
int h = (int) ((t / (1000*60*60)) % 24);
String dt="", dh, ds, dm;
if(h>0)
{
dh=Integer.toString(h);
if(h<10) dh="0"+dh;
dt=dt+dh+":";
}
if(m>=0)
{
dm=Integer.toString(m);
if(m<10) dm="0"+dm;
dt=dt+dm+":";
}
if(s>=0)
{
ds=Integer.toString(s);
if(s<10) ds="0"+ds;
dt=dt+ds;
}
return dt;
}
public void showTost(String s)
{
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
tadapter.getFilter().filter(s);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
#Override
public void afterTextChanged(Editable s) {}
}
And the xml :
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/popupwrap"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#color/bdcolor">
<RelativeLayout
android:id="#+id/popup"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/bdcolor">
<EditText
android:id="#+id/etext"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColorHint="#color/bbcolor"
android:hint="SEARCH FILTER"
android:background="#drawable/etext"
android:textSize="24sp"
android:textCursorDrawable="#drawable/cursor"
android:textColor="#color/gcolor"
android:inputType="text"
android:layout_marginLeft="10dp"
android:layout_marginRight="80dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"/>
<ImageView
android:id="#+id/btn_addtoplay"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_marginBottom="10dp"
android:layout_marginRight="10dp"
android:src="#drawable/check1"
android:clickable="true"
android:layout_alignParentRight="true"
android:layout_marginTop="10dp"
android:layout_centerVertical="true"/>
</RelativeLayout>
<ListView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/lst_traki2add">
</ListView>
</LinearLayout>
The problem is that you are relying on the Checkbox view in each row to maintain the selection state for that row. You will also see strange behavior if you have a long list of songs, select some, and then scroll. Both of these problems are because ListView will recycle the views that are used to render the songs that are currently displayed rather than creating a new set of views for every row.
To solve this problem, you need to maintain the selection state yourself. You can do this with a bool[] or List<Boolean> that stores a flag for every song in your current data. Use this to set the background color and checkbox state rather than relying on the checkbox state to set the background color.
reason is simple - you have OnCheckedChangeListener which fires after every (un)check and is changing background. Everytime you call notifyDataSetChanged() whole list will be redrawn, so background color will be again set with if(position1 %2 == 1) condition in getView method, but listener won't fire again. check out his code with manual listener call
CompoundButton.OnCheckedChangeListener listener = new CompoundButton.OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
if (cb_plus.isChecked())
{
cb_plus.setBackgroundResource(R.drawable.x2);
txt.setTextColor(context.getResources().getColor(R.color.bdcolor));
rowView.setBackgroundResource(R.color.acolor);
if(piosenki.get(album.get(position1)) != null) // won't duplicate
piosenki.add(album.get(position1));
}
else
{
cb_plus.setBackgroundResource(R.drawable.plus);
txt.setTextColor(context.getResources().getColor(R.color.gcolor));
if(position1 %2 == 1) rowView.setBackgroundResource(R.color.bbcolor);
else rowView.setBackgroundResource(R.color.bpcolor);
piosenki.remove(album.get(position1));
}
}
}
boolean isAdded = ...;
cb_plus.setChecked(isAdded);
cb_plus.setOnCheckedChangeListener(listener); // set listener after setting (un)checked
listener.onCheckedChanged(cb_plus, isAdded); // manual call
isAdded is your condition for CheckBox checked or not, problably piosenki.contains(album.get(position1)); or piosenki.get(album.get(position1)) != null;. you can also get rid of few duplicated lines from getView method, like those with background or textcolor setting - these will be called inside manual listener call
PS. also change piosenki to songs ;)

Replace spinner with dynamically added N number of buttons

Trying to replace spinner with buttons dynamically populated from database.
Normally spinner use array adapter and built-in List Item Layouts "android.R.layout.simple_spinner_item"etc. How should it be modified if instead of spinner you want to populate buttons?
How in the startQuiz() method Spinner spinnerDifficulty.getSelectedItem(); can be replaced with button index?
HERE HOW IT WORKED WITH SPINNER
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_starting_screen);
spinnerDifficulty = findViewById(R.id.spinner_quizlist);
loadDifficulties();
Button startTest = findViewById(R.id.start_test);
startTest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startQuiz();
}
});
}
private void startQuiz() {
ListQuiz selectedLevel = (ListQuiz) spinnerDifficulty.getSelectedItem();
int LevelListID = selectedLevel.getId();
String quizListName = selectedLevel.getName();
Intent intent = new Intent(StartingScreenActivity.this, MainActivity.class);
intent.putExtra(EXTRA_DIFFICULTY_ID, LevelListID);
intent.putExtra(EXTRA_DIFFICULTY_NAME, quizListName);
startActivityForResult(intent, REQUEST_CODE_QUIZ);
}
private void loadDifficulties(){
QuizDbHelper dbHelper = QuizDbHelper.getInstance(this);
List<ListQuiz> LevelList = dbHelper.getAllListQuiz();
ArrayAdapter<ListQuiz> adapterLevelList = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, LevelList); adapterLevelList.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerDifficulty.setAdapter(adapterLevelList);
}
Modifications done, so far...
private ArrayAdapter <ListQuiz> adapter;
private Button autobutton;
public int categorySize;
private List<ListQuiz> categoryName;
private LinearLayout QuizListLayout;
private Button levelButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_starting_screen);
autobutton = findViewById(R.id.autobutton);
loadDifficulties();
QuizListLayout = findViewById(R.id.layoutForButtons);
for(int i=0; i<categorySize;i++){
levelButton =new Button(this);
levelButton.setText("" + categoryName.get(i));
levelButton.setId(i);
final int index = i;
levelButton.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
levelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startQuiz();
}
});
QuizListLayout.addView(levelButton);
}
}
//startQuiz still same
private void startQuiz() {
ListQuiz selectedLevel = (ListQuiz) spinnerDifficulty.getSelectedItem();
int LevelListID = selectedLevel.getId();
String quizListName = selectedLevel.getName();
Intent intent = new Intent(StartingScreenActivity.this, MainActivity.class);
intent.putExtra(EXTRA_DIFFICULTY_ID, LevelListID);
intent.putExtra(EXTRA_DIFFICULTY_NAME, quizListName);
startActivityForResult(intent, REQUEST_CODE_QUIZ);
}
private void loadDifficulties(){
QuizDbHelper dbHelper = QuizDbHelper.getInstance(this);
List<ListQuiz> LevelList = dbHelper.getAllListQuiz();
categorySize = dbHelper.getAllListQuiz().size();
categoryName = dbHelper.getAllListQuiz();
buttonlayout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="#+id/layoutForButtons">
</LinearLayout>
you can add buttons dynamically to your layout just add linearLayout in your XML file where you wants to add buttons.
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="#+id/layoutForButtons">
</LinearLayout>
Create a varible of LinearLyout
LinearLayout layoutForButtons;
......
......
now initliase the varible in oncreate
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_starting_screen);
layoutForButtons = findViewById(R.id.layoutForButtons);
.....
addingButtonsDynamically(numberOfButtons);
}
public void addingButtonsDynamically(int numberOfButtons){
// for adding n number of buttons
for(int i=0; i<numberOfButtons;i++){
Button buttton=new Button(this);
button.setText("Button" + i);
button.setId(i);
button.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
// adding button to layout
layoutForButtons.addView(button);
}
}

How to add a variable number of TextViews and EditViews in activity

I'm currently trying to add a user-defined number of TextViews and EditText to an activity, but can't seem to do it other than hard-coding it by creating a variety of different activities.
The objective of this activity is to take the names of the players, the number of which is relayed by the intent extra from the preceding activity.
I'm trying to add both a TextView saying "Player X: " and an EditText to type the name of the player for each player
I know from this post: How to create a variable number of textviews in android that I have to do this programmatically, however, it does not seem to work for me (the activity remains blank when tested)
I have tried creating a temp LinearLayout to which I add the two views in a for(), still nothing.
Any ideas? Am I on the right track?
Best regards
[EDIT] Code is here :
public class players extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_players);
Bundle extras = new Bundle();
final int numPlayers = extras.getInt("num");
final LinearLayout myLayout = findViewById(R.id.lin_Re);
final ArrayList<Player> players = new ArrayList<>();
int size = numPlayers; // total number of TextViews to add
TextView[] tv = new TextView[size];
TextView temp;
EditText[] et = new EditText[size];
EditText temp2;
LinearLayout temp3;
for (int i = 0; i < size; i++)
{
temp = new TextView(this);
temp2 = new EditText(this);
temp3 = new LinearLayout(this);
temp.setText("Player " + i + " : "); //arbitrary task
// add the textview to the linearlayout
temp3.addView(temp);
temp3.addView(temp2);
tv[i] = temp;
et[i] = temp2;
myLayout.addView(temp3);
}
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
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:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
android:id="#+id/lin_Re">
</LinearLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/b_send"/>
</LinearLayout>
There is 2 way to achieve this:
1. Use a RecyclerView [Recommended]
2. Add TextView and EditText ( which is nested in a Horizontal LinearLayout) into a Vertical LinearLayout nested in a ScrollView programmatically
The first solution I describe below is quite simple if you're familiar with RecyclerView or ListView, the second solution (your current track) is a bit tricky but still achievable.
Solution 1:
MainActivity
public class MainActivity extends AppCompatActivity {
RecyclerView mPlayerList;
List<String> mPlayerNames;
PlayerAdapter mAdapter;
EditText mInput;
Button mCreateButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPlayerNames = new ArrayList<>();
// setup recycler view
mPlayerList = findViewById(R.id.player_list);
mPlayerList.setLayoutManager(new LinearLayoutManager(this));
mAdapter = new PlayerAdapter();
mPlayerList.setAdapter(mAdapter);
// setup input EditText
mInput = findViewById(R.id.input);
// setup Create button
mCreateButton = findViewById(R.id.create_button);
mCreateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// clear old player names
mPlayerNames.clear();
// read user input: number of player:
String input = mInput.getText().toString();
int numberOfPlayer;
try {
numberOfPlayer = Integer.parseInt(input);
} catch (NumberFormatException e) {
Toast.makeText(MainActivity.this, "Invalid input!!!", Toast.LENGTH_SHORT).show();
return;
}
for (int i = 0; i < numberOfPlayer; ++i) {
mPlayerNames.add("Player #" + (i + 1));
}
// make change on recycler view
mAdapter.notifyDataSetChanged();
// dismiss keyboard
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mInput.getWindowToken(), 0);
}
});
}
private class PlayerAdapter extends RecyclerView.Adapter<PlayerAdapter.PlayerHolder> {
#Override
public PlayerHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(MainActivity.this).inflate(R.layout.item_layout, parent, false);
return new PlayerHolder(v);
}
#Override
public void onBindViewHolder(PlayerHolder holder, int position) {
holder.bind(mPlayerNames.get(position));
}
#Override
public int getItemCount() {
return mPlayerNames.size();
}
public class PlayerHolder extends RecyclerView.ViewHolder {
TextView mPlayerLabel;
EditText mPlayerName;
public PlayerHolder(View itemView) {
super(itemView);
mPlayerLabel = itemView.findViewById(R.id.player_label);
mPlayerName = itemView.findViewById(R.id.player_name);
}
public void bind(String playerName) {
mPlayerLabel.setText(playerName);
mPlayerName.setHint("Name of " + playerName);
}
}
}
}
The sample project can be found here:
https://github.com/raiytu4/stackcase004

How to add icon for child node?

I use this lib. I want add icon for any child. But i don't know how i can do it.please help me.thanks any body.i read sample but ..this is my code.please read link
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TreeNode root = TreeNode.root();
final TreeNode parent = new TreeNode("Melk");
final TreeNode child0 = new TreeNode("Build_1");
TreeNode child1 = new TreeNode("Build_2");
TreeNode child_1 = new TreeNode("Aparteman_1");
TreeNode child_3 = new TreeNode("Aparteman_2");
TreeNode child_4 = new TreeNode("Senfi_1");
TreeNode child_5 = new TreeNode("Senfi_2");
child_1.addChildren(child_4, child_5);
child0.addChildren(child_1, child_3);
parent.addChildren(child0, child1);
root.addChild(parent);
Button del = (Button) findViewById(R.id.del);
parent.setClickListener(new TreeNode.TreeNodeClickListener() {
#Override
public void onClick(TreeNode node, Object value) {
Toast.makeText(getApplicationContext(),"",Toast.LENGTH_LONG).show();
}
});
LinearLayout containerView = (LinearLayout) findViewById(R.id.m);
AndroidTreeView tView = new AndroidTreeView(getApplicationContext(), root);
containerView.addView(tView.getView());
}
}
post edited.i need your help.
You have to use custom adapter as it use for default android listview only difference is to extend TreeNode.BaseNodeViewHolder and overwrite createNodeView
this is a structure
public class MyHolder extends TreeNode.BaseNodeViewHolder<IconTreeItem> {
...
#Override
public View createNodeView(TreeNode node, IconTreeItem value) {
final LayoutInflater inflater = LayoutInflater.from(context);
final View view = inflater.inflate(R.layout.layout_profile_node, null, false);
TextView tvValue = (TextView) view.findViewById(R.id.node_value);
tvValue.setText(value.text);
return view;
}
public static class IconTreeItem {
public int icon;
public String text;
}
}
for more information this tutorial will help you on how use custom adapter
https://github.com/codepath/android_guides/wiki/Using-an-ArrayAdapter-with-ListView

refresh activity with dynamic content

I have an activity with some dynamic content.
For each item of an array, there is a different content (number of textViews, checkboxes, ..)
The user clicks on a "save" button and then the screen has to refresh itself to display the content of the next item.
I was wondering if it was a good practice to reload my activity like this :
Intent refresh = new Intent(this, conflictActivity.class);
startActivity(refresh)
finish()
instead of removing all the views in my layouts, etc ...
I think it's easier to reload it.
Is there another way to do it ?
EDIT : added Code.
public class ConflicFieldTest extends Activity {
private int nbField;
private int nbChecked;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.conflict);
final Button saveButton = (Button) findViewById(R.id.save);
final LinearLayout leftLayout = (LinearLayout) findViewById(R.id.leftLayout);
final LinearLayout rightLayout = (LinearLayout) findViewById(R.id.rightLayout);
final TextView fieldName = new TextView(this);
final LinearLayout editLayoutRight = new LinearLayout(this);
final LinearLayout editLayoutLeft = new LinearLayout(this);
final LinearLayout fieldRight = new LinearLayout(this);
final LinearLayout fieldLeft = new LinearLayout(this);
final ArrayList<String> allIdInConflict = getAllIdInConflict();
for (int i = 0; i < allIdInConflict.size(); i++) {
new AccountSyncTask() {
#Override
public void onPostExecute(
final ArrayList<ArrayList<String>> result) {
nbField = 0;
nbChecked = 0;
final Map<String, Object> fieldsInConflict = conflict
.conflictWithFields(memoAccountMap,
serverAccountMap, modifiedAccountMap);
for (Iterator<Map.Entry<String, Object>> field = fieldsInConflict
.entrySet().iterator(); field.hasNext();) {
final Map.Entry<String, Object> entry = field.next();
fieldName.setText(entry.getKey() + " : ");
final EditText[] editTextArrayRight = new EditText[fieldsInConflict
.size()];
final EditText[] editTextArrayLeft = new EditText[fieldsInConflict
.size()];
final CheckBox[] checkboxRight = new CheckBox[fieldsInConflict
.size()];
final CheckBox[] checkboxLeft = new CheckBox[fieldsInConflict
.size()];
checkboxRight[nbField] = new CheckBox(
ConflicFieldTest.this);
checkboxLeft[nbField] = new CheckBox(
ConflicFieldTest.this);
editLayoutLeft.setGravity(Gravity.CENTER_HORIZONTAL);
editLayoutRight.setGravity(Gravity.CENTER_HORIZONTAL);
fieldRight.setGravity(Gravity.CENTER_HORIZONTAL);
fieldLeft.setGravity(Gravity.CENTER_HORIZONTAL);
editLayoutRight.setOrientation(LinearLayout.HORIZONTAL);
fieldRight.setOrientation(LinearLayout.VERTICAL);
fieldLeft.setOrientation(LinearLayout.VERTICAL);
rightLayout
.addView(
editLayoutRight,
new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
leftLayout
.addView(
editLayoutLeft,
new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
editTextArrayRight[nbField] = new EditText(
ConflicFieldTest.this);
editTextArrayRight[nbField].setText((String) entry
.getValue());
editTextArrayRight[nbField].setTextColor(Color.BLACK);
editTextArrayRight[nbField].setFocusable(false);
editTextArrayRight[nbField].setClickable(false);
editTextArrayRight[nbField].setWidth(180);
editTextArrayRight[nbField].setPadding(0, 10, 0, 0);
editTextArrayLeft[nbField] = new EditText(
ConflicFieldTest.this);
editTextArrayLeft[nbField]
.setText((String) serverAccountMap.get(entry
.getKey()));
editTextArrayLeft[nbField].setTextColor(Color.BLACK);
editTextArrayLeft[nbField].setFocusable(false);
editTextArrayLeft[nbField].setClickable(false);
editTextArrayLeft[nbField].setWidth(180);
editTextArrayLeft[nbField].setPadding(0, 10, 0, 0);
final int i1 = nbField;
checkboxLeft[i1]
.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
checkboxRight[i1]
.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
editLayoutLeft.addView(fieldName);
editLayoutRight
.addView(
editTextArrayRight[nbField],
new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
editLayoutLeft
.addView(
editTextArrayLeft[nbField],
new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
editLayoutRight.addView(checkboxRight[nbField]);
editLayoutLeft.addView(checkboxLeft[nbField]);
nbField++;
}
saveButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
//save data & update UI
}
}
.execute(appState.getSessionName(), id, "getObjectOnServer");
}
}
Sorry for the code, it is a litle bit dirty (i have deleted some parts), i am reworking it.
int flag = 0;
public void updateUI() {
if(flag == 0) {
//your normal codes...
} else {
//display view with user given data
}
}
Call this function in oncreate. At first flag will be set to zero. When u enter the data in textview and tick checkboxes, update the flag with some value. Then on save Button click call this function again. Now flag is set. So it will display the updated UI.
I think this will give u an idea..

Categories

Resources