Here, I try to check only one radio button, But I have multiple checked radio button. How can I implement check only one.
starRadioBtn = new RadioButton[starCount.size()];
radioGroup = new RadioGroup(StarCountActivity.this);
radioGroup.setId(1);
radioGroup.setOrientation(RadioGroup.VERTICAL);
for (int i = 0;i<starCount.size(); i++){
starRadioBtn[i] = new RadioButton(StarCountActivity.this);
object = starCount.get(i);
starRadioBtn[i].setText(object.getName());
starRadioBtn[i].setId(i);
radioGroup.addView(starRadioBtn[i]);
}
radioLayout.addView(radioGroup);
Try this
xml layout
<LinearLayout
android:id="#+id/linear1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:orientation="vertical">
<RadioGroup
android:id="#+id/radiogroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:orientation="vertical" />
</LinearLayout>
my activity code
RadioGroup rg = (RadioGroup) findViewById(R.id.radiogroup);
RadioButton[] rb = new RadioButton[items.size()];
for (int i = 0; i < items.size(); i++) {
rb[i] = new RadioButton(this);
rg.addView(rb[i]);
rb[i].setText(items.get(i).getName());
}
Note:Remove this
radioGroup.setId(1);
code...
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup rg, int checkedId) {
for(int i=0; i<rg.getChildCount(); i++) {
RadioButton btn = (RadioButton) rg.getChildAt(i);
if(btn.getId() == checkedId) {
String text = btn.getText().toString();
// do something with text
Toast.makeText(demo.this,text,Toast.LENGTH_SHORT).show();
return;
}
}
}
});
Can you try out this code:
for (int row = 0; row < 1; row++) {
for (int i = 0;i<starCount.size(); i++){
starRadioBtn[i] = new RadioButton(StarCountActivity.this);
object = starCount.get(i);
starRadioBtn[i].setText(object.getName());
starRadioBtn[i].setId(i);
radioGroup.addView(starRadioBtn[i]);
}
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {});
}
Related
I want to create an app on that the idea is click on the button and changing an image. every time I click on the button an imageview change (dynamic imageview). I'm trying to do that but when I run the code below the first imageview is loaded and when I press the button, the first imageview jump to last imageview, ignoring two imageviews among them. What's wrong?
This is my code:
SEGUNDATELA. JAVA:
public class SegundaTela extends AppCompatActivity {
private Integer [] imagens = new Integer[]{R.drawable.tabeladia2, R.drawable.tabeladia3, R.drawable.tabeladia4, R.drawable.tabeladia5};
private RadioGroup radioGroup;
private RadioButton sim;
private RadioButton nao;
private Button proxima;
private ImageView img;
private int i=0;
private Integer [] dados= new Integer[4];
private int soma =0;
private int j;
private int inicio;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_segunda_tela);
img = findViewById(R.id.imageView);
proxima = findViewById(R.id.proximaId);
radioGroup = findViewById(R.id.RadioGroupId);
sim = findViewById(R.id.simId);
nao = findViewById(R.id.naoId);
if (sim.isChecked()) {
inicio = 1;
} else if (nao.isChecked()) {
inicio = 0;
}
proxima.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (i < 4) {
++i;
j = (i - 1);
switch (j) {
case 0:
if (sim.isChecked()) {
img.setImageResource(imagens[j]);
dados[j] = 2;
} else if (nao.isChecked()) {
img.setImageResource(imagens[j]);
dados[j] = 0;
}
break;
case 1:
if (sim.isChecked()) {
img.setImageResource(imagens[j]);
dados[j] = 4;
} else if (nao.isChecked()) {
img.setImageResource(imagens[j]);
dados[j] = 0;
}
break;
case 2:
if (sim.isChecked()) {
img.setImageResource(imagens[j]);
dados[j] = 8;
} else if (nao.isChecked()) {
img.setImageResource(imagens[j]);
dados[j] = 0;
}
break;
case 3:
if (sim.isChecked()) {
img.setImageResource(imagens[j]);
dados[j] = 16;
} else if (nao.isChecked()) {
img.setImageResource(imagens[j]);
dados[j] = 0;
}
break;
}
radioGroup.clearCheck();
} else {
soma = dados[0] + dados[1] + dados[2] + dados[3] + inicio;
Intent i = new Intent(SegundaTela.this, MainActivity.class);
i.putExtra("soma", soma);
startActivity(i);
}
}
});
}
}
SEGUNDATELA.MML
<?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"
tools:context=".MainActivity">
<Button
android:id="#+id/proximaId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
android:text="proxima"
app:layout_constraintBottom_toTopOf="#+id/imageView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
android:scaleType="fitXY"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/tabeladia1" />
<RadioGroup
android:id="#+id/RadioGroupId"
android:layout_width="98dp"
android:layout_height="86dp"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toTopOf="#+id/imageView"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<RadioButton
android:id="#+id/simId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Sim" />
<RadioButton
android:id="#+id/naoId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Não" />
</RadioGroup>
Ever time you execute onClick() the entire for loop will execute. That is why. If you only want it to proceed one image at the time you need to find a different solution that allows you to keep state (knowing current image) between the "clicks".
You need to remove the for loop and increment everytime the button is clicked.
Use this if you want the images to be shown in a loop.
public class MainActivity extends AppCompatActivity {
private int [] imagens = {R.drawable.tabeladia2, R.drawable.tabeladia3,
R.drawable.tabeladia4, R.drawable.tabeladia5};
private Button proxima;
private ImageView img;
private Integer currentImg;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
proxima = findViewById(R.id.proximaId);
img = findViewById(R.id.imageView);
proxima.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (currentImg != null && currentImg < 3) {
currentImg++;
} else {
currentImg = 0;
}
img.setImageResource(imagens[currentImg]);
}
});
}
}
Use this if you don't want the images to be looped
public class MainActivity extends AppCompatActivity {
private int [] imagens = {R.drawable.tabeladia2, R.drawable.tabeladia3,
R.drawable.tabeladia4, R.drawable.tabeladia5};
private Button proxima;
private ImageView img;
private Integer currentImg;
private int[] intArray = new int[4];
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
proxima = findViewById(R.id.proximaId);
img = findViewById(R.id.imageView);
proxima.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (currentImg != null) {
if (currentImg < 3) {
currentImg++;
if(currentImg == 1){
intArray[1] = 2;
}else if(currentImg == 2){
intArray[2] = 4;
}else if(currentImg == 3){
intArray[3] = 8;}
img.setImageResource(imagens[currentImg]);
}else{
//handle last image reached condition
Toast.makeText(MainActivity.this, "Last image reached", Toast.LENGTH_SHORT).show();
}
} else {
currentImg = 0;
intArray[0] = 1;
img.setImageResource(imagens[currentImg]);
}
}
});
}
}
Using Case Statement and RadioButtons.
public class SegundaTela extends AppCompatActivity {
private Integer[] imagens = new Integer[]{R.drawable.tabeladia2, R.drawable.tabeladia3, R.drawable.tabeladia4, R.drawable.tabeladia5};
private RadioGroup radioGroup;
private RadioButton sim;
private RadioButton nao;
private Button proxima;
private ImageView img;
private Integer i;
private int soma = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_segunda_tela);
img = findViewById(R.id.imageView);
proxima = findViewById(R.id.proximaId);
radioGroup = findViewById(R.id.RadioGroupId);
sim = findViewById(R.id.simId);
nao = findViewById(R.id.naoId);
proxima.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!sim.isChecked() && !nao.isChecked()) {
Toast.makeText(SegundaTela.this, "Select an option", Toast.LENGTH_SHORT).show();
return;
}
if (i != null) {
if (i < 5) {
switch (i) {
case 0:
if (sim.isChecked()) {
img.setImageResource(imagens[i]);
//dados[j] = 2;
soma = soma + 2;
} else if (nao.isChecked()) {
img.setImageResource(imagens[i]);
//dados[j] = 0;
soma = soma + 0;
}
break;
case 1:
if (sim.isChecked()) {
img.setImageResource(imagens[i]);
//dados[j] = 4;
soma = soma + 4;
} else if (nao.isChecked()) {
img.setImageResource(imagens[i]);
//dados[j] = 0;
soma = soma + 0;
}
break;
case 2:
if (sim.isChecked()) {
img.setImageResource(imagens[i]);
//dados[j] = 8;
soma = soma + 8;
} else if (nao.isChecked()) {
img.setImageResource(imagens[i]);
//dados[j] = 0;
soma = soma + 0;
}
break;
case 3:
if (sim.isChecked()) {
img.setImageResource(imagens[i]);
//dados[j] = 16;
soma = soma + 16;
} else if (nao.isChecked()) {
img.setImageResource(imagens[i]);
//dados[j] = 0;
soma = soma + 0;
}
break;
case 4:
/*if (sim.isChecked()) {
//dados[j] = 16;
soma = soma + 32;
} else if (nao.isChecked()) {
//dados[j] = 0;
soma = soma + 0;
}*/
Intent i = new Intent(SegundaTela.this, MainActivity.class);
i.putExtra("soma", soma);
startActivity(i);
break;
}
++i;
Toast.makeText(SegundaTela.this, "soma: " + soma, Toast.LENGTH_SHORT).show();
radioGroup.clearCheck();
} /*else {
//soma = dados[0] + dados[1] + dados[2] + dados[3] + inicio;
Intent i = new Intent(SegundaTela.this, MainActivity.class);
i.putExtra("soma", soma);
startActivity(i);
}*/
}else {
if (sim.isChecked()) {
//inicio = 1;
soma = soma + 1;
} else if (nao.isChecked()) {
//inicio = 0;
soma = soma + 0;
}
i = 0;
radioGroup.clearCheck();
}
}
});
}
}
Six RadioButtons aligned as 3 columns and 2 rows in a RadioGroup, so 6 RB-s in RG. If user selects a RB, right under it image1 and text1 are shown and under alternated RB-s image1 and text2 are also shown. User may select any RB. The proper behavior looks like that https://photos.app.goo.gl/NEqTaxsY6daxD3kJA
<android.support.design.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/bg">
<include layout="#layout/app_bar" />
<fragment
android:id="#+id/refreshLayoutFragment"
class="kz.fingram.RefreshLayoutFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:layout="#layout/fragment_refresh_layout" />
<LinearLayout
android:id="#+id/root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingEnd="#dimen/activity_margin"
android:paddingLeft="#dimen/activity_margin"
android:paddingRight="#dimen/activity_margin"
android:paddingStart="#dimen/activity_margin"
android:paddingTop="#dimen/activity_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/when_u_want_money"
android:textAppearance="#style/TextAppearance.Medium" />
<RadioGroup
android:id="#+id/months"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:background="#drawable/primary_transparent_round_bg"
android:orientation="horizontal"
app:setOnCheckedChangeListener="#{viewModel.mMonthOnCheckedChangeListener}" />
<LinearLayout
android:id="#+id/thisIs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="3dp"
android:orientation="horizontal" />
<RadioGroup
android:id="#+id/months2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:background="#drawable/primary_transparent_round_bg"
android:orientation="horizontal"
app:setOnCheckedChangeListener="#{viewModel.mMonthOnCheckedChangeListener2}" />
<LinearLayout
android:id="#+id/thatIs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="3dp"
android:orientation="horizontal" />
<Button
style="#style/Button.Primary"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:enabled="#{viewModel.mIsNextEnabled}"
android:onClick="#{viewModel::nextOnClick}"
android:text="#string/next" />
</LinearLayout>
</android.support.design.widget.CoordinatorLayout>
Java code:
RadioGroup rg1 = findViewById(R.id.months);
rg1.setOnCheckedChangeListener(null);
rg1.clearCheck();
rg1.setOnCheckedChangeListener(mMonthOnCheckedChangeListener);
View view = radioGroup.findViewById(i);
if (view != null) {
mMonth = (TeamFreeMonth) view.getTag();
}
selectMonth();
checkButtonsState();
public final class OptionsActivity extends BaseAppCompatActivity {
private ActivityOptionsBinding mBinding;
public static void show(#NonNull final Context ctx) {
StorageHelper.getInstance().setInvited(false);
BaseAppCompatActivity.show(ctx, OptionsActivity.class, true, false);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBinding = DataBindingUtil.setContentView(this, R.layout.activity_options);
setupToolbar();
mBinding.setViewModel(new ViewModel());
}
public final class ViewModel extends BaseObservable {
private static final int TERM_6_MONTH_ID = 1;
private static final int INSTALLMENT_10000_ID = 1;
private final RefreshLayoutFragment mRefreshLayout;
public boolean mIsNextEnabled;
public TeamFreeMonth mMonth;
private TeamFreeMonth[] mMonths;
ViewModel() {
mMonth = null;
mMonths = null;
mRefreshLayout = (RefreshLayoutFragment) getSupportFragmentManager()
.findFragmentById(R.id.refreshLayoutFragment);
mRefreshLayout.setup(mBinding.root, new RefreshLayoutFragment.Callback() {
#Override
public void reload() {
try {
loadData();
} catch (Exception e) {
ExceptionHelper.displayException(OptionsActivity.this, e);
}
}
});
public RadioGroup.OnCheckedChangeListener mMonthOnCheckedChangeListener =
new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, #IdRes int i) {
if (i != -1) {
RadioGroup rg2 = findViewById(R.id.months2);
rg2.setOnCheckedChangeListener(null);
rg2.clearCheck();
rg2.setOnCheckedChangeListener(mMonthOnCheckedChangeListener2);
View view = radioGroup.findViewById(i);
if (view != null) {
mMonth = (TeamFreeMonth) view.getTag();
}
selectMonth();
checkButtonsState();
}
}
};
public RadioGroup.OnCheckedChangeListener mMonthOnCheckedChangeListener2 =
new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, #IdRes int i) {
if (i != -1) {
RadioGroup rg1 = findViewById(R.id.months);
rg1.setOnCheckedChangeListener(null);
rg1.clearCheck();
rg1.setOnCheckedChangeListener(mMonthOnCheckedChangeListener);
View view = radioGroup.findViewById(i);
if (view != null) {
mMonth = (TeamFreeMonth) view.getTag();
}
selectMonth();
checkButtonsState();
}
}
};
private void refreshMonths() {
mBinding.months.removeAllViews();
mBinding.months.clearCheck();
mBinding.months2.removeAllViews();
mBinding.months2.clearCheck();
mBinding.thisIs.removeAllViews();
mBinding.thatIs.removeAllViews();
final TeamFreeMonth oldMonth = mMonth;
mMonth = null;
checkButtonsState();
if (mMonths == null) {
return;
}
final TeamFreeMonth[] months = mMonths;
if (months.length == 0) {
return;
}
int halfMonths = months.length / 2;
for (int i = 0; i < halfMonths; i++) {
final String date = UtilitiesHelper.dateToStr(months[i].getDate(), Constants.DATE_FORMAT_LLLL);// Получили месяц от даты
final String date2 = UtilitiesHelper.dateToStr(months[i + halfMonths].getDate(), Constants.DATE_FORMAT_LLLL);// Получили месяц от даты
if (TextUtils.isEmpty(date) || TextUtils.isEmpty(date2)) {
continue;
}
final RadioButton rb = (RadioButton) LayoutInflater.from(OptionsActivity.this).inflate(R.layout.radio_button_tab, mBinding.months, false);
rb.setId(i);
rb.setTag(months[i]);
final SpannableString btnCaption = new SpannableString(date);
btnCaption.setSpan(new AbsoluteSizeSpan(getResources().getDimensionPixelSize(R.dimen.font_size_18)), 0, date.length(), 0);
rb.setText(btnCaption);
final RadioButton rb2 = (RadioButton) LayoutInflater.from(OptionsActivity.this).inflate(R.layout.radio_button_tab, mBinding.months2, false);
rb2.setId(i + halfMonths);
rb2.setTag(months[i + halfMonths]);
final SpannableString btnCaption2 = new SpannableString(date2);
btnCaption2.setSpan(new AbsoluteSizeSpan(getResources().getDimensionPixelSize(R.dimen.font_size_18)), 0, date2.length(), 0);
rb2.setText(btnCaption2);
if (i == 0) {
rb.setBackgroundResource(R.drawable.ll_radio_button_start);
rb2.setBackgroundResource(R.drawable.ll_radio_button_start);
} else if (i == halfMonths - 1) {
rb.setBackgroundResource(R.drawable.ll_radio_button_end);
rb2.setBackgroundResource(R.drawable.ll_radio_button_end);
}
mBinding.months.addView(rb);
mBinding.months2.addView(rb2);
TextView thisIs = (TextView) LayoutInflater.from(OptionsActivity.this).inflate(R.layout.options_this_is_item, mBinding.thisIs, false);
thisIs.setId(rb.getId());
thisIs.setText(getString(R.string.thisIs));
thisIs.setVisibility(View.INVISIBLE);
mBinding.thisIs.addView(thisIs);
TextView thatIs = (TextView) LayoutInflater.from(OptionsActivity.this).inflate(R.layout.options_that_is_item, mBinding.thatIs, false);
thatIs.setId(rb2.getId());
thatIs.setText(getString(R.string.thatIs));
thatIs.setVisibility(View.INVISIBLE);
mBinding.thatIs.addView(thatIs);
if (oldMonth != null && UtilitiesHelper.isDateEquals(oldMonth.getDate(), months[i].getDate())) {
mBinding.months.check(rb.getId());
mBinding.months2.check(rb2.getId());
}
}
selectMonth();
}
private void selectMonth()
{
int selectedId1 = mBinding.months.getCheckedRadioButtonId();
int selectedId = selectedId1 !=-1 ? selectedId1 : mBinding.months2.getCheckedRadioButtonId();
int n = mBinding.months.getChildCount();
List<TextView> views = new ArrayList<TextView>();
for (int i = 0; i < n; i++) {
views.add(i, (TextView) mBinding.thisIs.getChildAt(i));
views.add(i+3, (TextView) mBinding.thatIs.getChildAt(i));
}
int length = views.size();
for (int i = 0; i < length; i++) {
TextView child = views.get(i);
}
private void checkButtonsState() {
mIsNextEnabled = mMonth != null;
notifyChange();
}
public void nextOnClick(final View view) {
try {
final TeamFreeMonth[] months = mMonths;
if (mMonth == null || months == null || months.length == 0) {
throw new Exception(getString(R.string.enter_month));
}
SettingsHelper.setTermId(OptionsActivity.this, TERM_6_MONTH_ID);//
SettingsHelper.setTermRateId(OptionsActivity.this, mMonth.getTermRateId());//
SettingsHelper.setInstallmentId(OptionsActivity.this, INSTALLMENT_10000_ID);
SettingsHelper.setGoalDateInMillis(OptionsActivity.this, mMonth.getDate().getTime());//дата получения
SettingsHelper.setFirstGoalDateInMillis(OptionsActivity.this, months[0].getDate().getTime());
SettingsHelper.setGoalSum(OptionsActivity.this, mMonth.getSum());
BaseAppCompatActivity.show(OptionsActivity.this, SetGoalActivity.class, true, false);
} catch (Exception e) {
ExceptionHelper.displayException(OptionsActivity.this, e);
}
}
private void loadData() {
try {
final AsyncTask<Void, Void, TeamFreeMonth[]> task = new AsyncTask<Void, Void, TeamFreeMonth[]>() {
private Exception mError = null;
#Override
protected void onPreExecute() {
mRefreshLayout.setRefreshing(true);
}
#Override
protected TeamFreeMonth[] doInBackground(Void... params) {
try {
TeamFreeMonth[] months = ServerHelper.getInstance().syncGetOptionMonths(OptionsActivity.this, TERM_6_MONTH_ID, INSTALLMENT_10000_ID);
if (months != null && months.length > 0)
return months;
} catch (Exception e) {
mError = e;
}
return null;
}
#Override
protected void onPostExecute(TeamFreeMonth[] result) {
try {
if (mError != null) {
throw mError;
}
mMonths = result;
refreshMonths();
checkButtonsState();
mRefreshLayout.setRefreshing(false);
} catch (Exception e) {
mRefreshLayout.setError(e);
}
}
};
task.execute();
} catch (Exception e) {
mRefreshLayout.setError(e);
}
}
}
}
Image1 is always the same, while text1 and text2 differ. Text1 'You' is shown under the selected RB and text2 'Your friend' - under alternating RB-s.
The quetion still is how to show/hide image1 and text 1 or text 2 alternatively?
I can show/hide image1 and text-s under RB-s which is in the same column, but not alternating RB-s.
I have an activity which generates a scrollable list (let's say a column) of programmatically created buttons from a List which is the result of an sqlite table read and my problem is that as the List is growing (and so the number of buttons) the initial painting of the screen is becoming slow (at the moment is taking 3 seconds with 50 buttons to draw) so I'm looking for a solution to this.
At first I thought of using a thread (runnable, handler or whatever is best), let's say creating a new thread inside the For which iterates over the list but it's not working (or at least I'm not being able to make it to work) so my question is the next:
Starting from a List<> which is the most appropiate way to create a big set of scrollable buttons so users doesn't have such delay when accesing the screen.
Paginating could be an option, but I'd like to know about other possibilities first and leave that as a last resource.
Thanks, and below is my code.
public static void createButtons(LinearLayout llContainer,
List<TestType> TestTypes, List<Test> Tests,
int buttonFontSize) {
Context oContext = llContainer.getContext();
String strTheme = TMAppearance.getThemeFromPreferences(oContext);
testMe = ((ApplicationConfiguration)oContext.getApplicationContext());
int callerActivity = TestTypes!=null ? 2 : 1;
if (TestTypes!=null || Tests!=null) {
int lCols = strTheme.equals(testMe.theme_vivid) ? 1 : 2;
//int sourceElementIndex = 0;
int originListSize = calculateOriginalListSize(callerActivity, TestTypes, Tests);
int lRows = (int) Math.ceil((double)originListSize/lCols);
List<String> aStartColors = TMUtils_ThemeVivid.generateStartColorArray(lRows, oContext);
List<String> aEndColors = TMUtils_ThemeVivid.generateEndColorArray(lRows, oContext);
for (i = 0; i < lRows; i++) {
LinearLayout outerButtonLayout = generateOuterButtonLayout(oContext);
for (j = 0; j < lCols; j++) {
final Thread r = new Thread() {
public void run() {
LinearLayout innerButtonLayout = generateInnerButtonLayout(oContext);
outerButtonLayout.addView(innerButtonLayout, j);
if (sourceElementIndex<originListSize){
final TMButton oButton = new TMButton(oContext);
if (callerActivity==1) { //testMenu
setTestMenuButtonSettings(oButton, sourceElementIndex, Tests);
} else {
if (callerActivity==2) { //testTypeMenu
setTestTypeMenuButtonSettings(oButton, sourceElementIndex, TestTypes);
}
}
if (strTheme.equals(testMe.theme_vivid)){
oButton.fontSize = buttonFontSize;
oButton.gradientStartColor = aStartColors.get(i);
oButton.gradientEndColor = aEndColors.get(i);
}else{
if (strTheme.equals(testMe.theme_purple)){
oButton.gradientStartColor = testMe.btnStartColor_purple;
oButton.gradientEndColor = testMe.btnEndColor_purple;
}
}
configureButton(oButton, callerActivity);
oButton.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
Context oContext = v.getContext();
TMButton oButton = (TMButton) v;
int callerActivity = Integer.valueOf(v.getTag().toString().split("#")[0]);
String sourceId = String.valueOf(v.getTag().toString().split("#")[1]);
if(event.getAction() == MotionEvent.ACTION_DOWN) { //pressed
setButtonPressed(oButton);
TMSound.playButtonSound(oContext);
} else if (event.getAction() == MotionEvent.ACTION_UP) { //released
setButtonReleased(oButton);
startTargetActivity(callerActivity, sourceId, oContext);
}
return true;
}
});
TMAppearance.doButtonAnimation(oContext, oButton, i);
innerButtonLayout.addView(oButton);
sourceElementIndex++;
}
}
};
r.run();
}
llContainer.addView(outerButtonLayout);
}
}
}
0X0nosugar is correct. A RecycleView will provide better performance, but many beginners have more difficulty implementing it and with only 50 buttons performance shouldn't really be an issue. And although I generally like to abide by the rule 'Use the best available solution' I think it is still appropriate to learn how to implement the ListView. So...
You will need to create a custom adapter:
public class MyListDataAdapter extends ArrayAdapter<MyListData> {
private static final String TAG = "MyListDataAdapter";
public MyListDataAdapter(Context context, ArrayList<MyListData> data) {
super(context, 0, data);
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
final MyListData data = getItem(position);
if(convertView == null){
convertView = LayoutInflater.from(getContext()).inflate(R.layout.edit_list_item, parent, false);
}
// Add a TextView if you need one
final TextView tvName = (TextView) convertView.findViewById(R.id.tvName);
Button btnEditTicketHolder = (Button) convertView.findViewById(R.id.btnEdit);
btnEditTicketHolder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
long userId = data.getUserId();
String fName = data.getFirstName();
Intent intent = new Intent(getContext(), EditActivity.class);
intent.putExtra("userId", userId);
intent.putExtra("fName", fName);
getContext().startActivity(intent);
}
});
String name = data.getFirstName();
tvName.setText(name);
return convertView;
}
}
Now you need your MyListData class to hold the data:
public class MyListData {
// Add more as you need
private long userId;
private String firstName;
public MyListData(){
}
public void setFirstName(String name){ this.firstName = name; }
public void setUserId(long id){ this.userId = id; }
public String getFirstName(){ return this.firstName; }
public long getUserId(){ return this.userId; }
}
Your custom ListView layout could look something like:
<?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"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
>
<TextView
android:id="#+id/tvName"
android:text="With Whom"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
>
<Button
android:id="#+id/btnEdit"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:paddingRight="10dp"
android:paddingLeft="10dp"
android:text="Edit"
android:backgroundTint="#color/colorAccent"
android:focusable="false"
/>
</LinearLayout>
</RelativeLayout>
In your Activity (eg. in the onCreate() method) where the ListView you will need to populate the data for the ListView. This should not be done on the UI Thread
ArrayList<MyListData> arrayListData = new ArrayList<MyListData>();
MyListDataAdapter adapter = new MyListDataAdapter(this, arrayListData);
for (MyListData g : result) {
adapter.add(g);
}
mLstMy.setAdapter(adapter);
Also in the activity where the ListView is to be maintained set up some onClick event handlers if you need them:
(I find that one of the small advantages of the ListView is that the onClick event is easier it implement than in the RecycleView)
mMyLst = (ListView) findViewById(lstMy);
mMyLst.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long l) {
MyListData data = (MyListData) parent.getItemAtPosition(position);
selectedName = data.getName();
Intent intent = new Intent(ShowListDataActivity.this, MainActivity.class);
startActivity(intent);
}
});
mMyLst.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
MyListData data = (MyistData) adapterView.getItemAtPosition(i);
selectedName = data.getFirstName();
selectedTicketPosition = i;
// removeValue is my own method for removing an entry from the
// list MyListData and then call adapter.notifyDataSetChanged();
removeValue(i);
return true;
}
});
I am new to android.I have table layout in XML and dynamically adding rows,i am trying to put dynamic rows into scrollview.please anyone help how to do.
Here my xml:
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
<include layout="#layout/header"
android:id="#+id/header" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tv_message"
android:textSize="18sp"
android:textAlignment="center"
android:background="#deb8"
android:layout_below="#id/header"
android:textColor="#000000"
android:text="Please Confirm the Quote and check for Errors "/>
<ScrollView
android:id="#+id/ScrollView03"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tv_message" >
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/tv_message"
android:id="#+id/table_orderfulfillment"
android:stretchColumns="*">
</TableLayout>
</ScrollView>
</Relative Layout>
Okay i have tried to Populate Tablelayout dynamically through String Array
here is the code: scrollview is also added.
public class MainActivity extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
String[] row = { "ROW1", "ROW2", "Row3", "Row4", "Row 5", "Row 6",
"Row 7"
};
String[] column = { "COLUMN1", "COLUMN2", "COLUMN3", "COLUMN4",
"COLUMN5", "COLUMN6"
};
int rl=row.length;
int cl=column.length;
ScrollView sv = new ScrollView(this);
TableLayout tableLayout = createTableLayout(row, column,rl, cl);
HorizontalScrollView hsv = new HorizontalScrollView(this);
hsv.addView(tableLayout);
sv.addView(hsv);
setContentView(sv);
}
private TableLayout createTableLayout(String [] rv, String [] cv,int rowCount, int columnCount)
{
// 1) Create a tableLayout and its params
TableLayout.LayoutParams tableLayoutParams = new TableLayout.LayoutParams();
TableLayout tableLayout = new TableLayout(this);
tableLayout.setBackgroundColor(Color.BLACK);
// 2) create tableRow params
TableRow.LayoutParams tableRowParams = new TableRow.LayoutParams();
tableRowParams.setMargins(1, 1, 1, 1);
tableRowParams.weight = 1;
for (int i = 0; i < rowCount; i++)
{
// 3) create tableRow
TableRow tableRow = new TableRow(this);
tableRow.setBackgroundColor(Color.BLACK);
for (int j= 0; j < columnCount; j++)
{
// 4) create textView
TextView textView = new TextView(this);
// textView.setText(String.valueOf(j));
textView.setBackgroundColor(Color.WHITE);
textView.setGravity(Gravity.CENTER);
String s1 = Integer.toString(i);
String s2 = Integer.toString(j);
String s3 = s1 + s2;
int id = Integer.parseInt(s3);
Log.d("TAG", "-___>"+id);
if (i ==0 && j==0)
{
textView.setText("0==0");
}
else if(i==0)
{
Log.d("TAAG", "set Column Headers");
textView.setText(cv[j-1]);
}
else if( j==0)
{
Log.d("TAAG", "Set Row Headers");
textView.setText(rv[i-1]);
}
else
{
textView.setText(""+id);
// check id=23
if(id==23)
{
textView.setText("ID=23");
}
}
// 5) add textView to tableRow
tableRow.addView(textView, tableRowParams);
}
// 6) add tableRow to tableLayout
tableLayout.addView(tableRow, tableLayoutParams);
}
return tableLayout;
}
}
output:
I'm using this code to load more data on scroll.!
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView,
int newState) {
super.onScrollStateChanged(recyclerView, newState);
// If scroll state is touch scroll then set userScrolled
// true
if (newState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
userScrolled = true;
}
}
#Override
public void onScrolled(RecyclerView recyclerView, int dx,
int dy) {
super.onScrolled(recyclerView, dx, dy);
// Here get the child count, item count and visibleitems
// from layout manager
visibleItemCount = mLayoutManager.getChildCount();
totalItemCount = mLayoutManager.getItemCount();
pastVisiblesItems = mLayoutManager
.findFirstVisibleItemPosition();
// Now check if userScrolled is true and also check if
// the item is end then update recycler view and set
// userScrolled to false
if (userScrolled
&& (visibleItemCount + pastVisiblesItems) == totalItemCount) {
userScrolled = false;
RefreshData(oldestPostId);
// implementScrollListener();
}
}
});
My android activity workout view displays a grid view. Each object of grid view either displays the name of an exercise and two buttons or it displays a exercise set and two buttons.This is what it looks like when I don't add buttons to each set.
Once I enable buttons to each set by commenting out deleteBtn.setVisibility(View.GONE); the activity displays this. changing the 3rd to last object to display an exercise instead of a set. (Scrolled down)
getLocation(int i) determines if an grid object is going to be an Exercise or set. location[0] determines the exercise and location1 if == 0 refers to exercise and location1 > 0 refers to an exercise set.
private int[] getLocation(int i) {
db = new DatabaseHelper(context);
int temp[] = {-1, -1};
int count = -1;
for (int we = 0; we < WE_TABLE.size(); we++) {
for (int s = 0; s < db.getSetCountByWEID(WE_TABLE.get(we).getID()) + 1; s++) {
count++;
if (count == i) {
//Log.e("Test","WE: " + we+ " S: " + s + " For: " + i);
temp[0] = we;
temp[1] = s;
db.closeDB();
return temp;
}
}
}
db.closeDB();
return temp;
}
public View getView(int position, View convertView, ViewGroup parent) {
int temp_p = position;
TextView tv;
View view = convertView;
if (view == null) {
totalObj++;
Obj = totalObj;
int[] location = getLocation(Obj - 1);
db = new DatabaseHelper(context);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.activity_workout_view_gridview, null);
tv = new TextView(context);
tv.setLayoutParams(new GridView.LayoutParams(GridView.LayoutParams.FILL_PARENT, GridView.LayoutParams.WRAP_CONTENT));
Button deleteBtn = (Button) view.findViewById(R.id.delete_btn);
Button addBtn = (Button) view.findViewById(R.id.add_btn);
tv = (TextView) view.findViewById(R.id.list_item_string);
String Exercises = (Obj + " " + location[0] + "," + location[1]);
Log.e("Test", "Location: " + location[0] + " , " + location[1] + " Number " + Obj);
if (location[1] == -1) {
} else if (location[1] == 0) {
WorkoutExercise WE = WE_TABLE.get(location[0]);
Exercises = WE.getExerciseName();
// addBtn.setVisibility(View.GONE);
//deleteBtn.setVisibility(View.GONE);
} else {
S_TABLE = db.getSets(WE_TABLE.get(location[0]).getID() + "");
Exercises = S_TABLE.get(location[1] - 1).getWeight() + "lbs " + S_TABLE.get(location[1] - 1).getReps() + " Reps";
addBtn.setVisibility(View.GONE);
//deleteBtn.setVisibility(View.GONE);
}
deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do something
}
});
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do something
}
});
tv.setText(Exercises);
db.closeDB();
}
return view;
}
And My XML for each row is:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/list_item_string"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:paddingLeft="8dp"
android:textSize="18sp"
android:textStyle="bold" />
<Button
android:id="#+id/delete_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="0dp"
android:text="Dele" />
<Button
android:id="#+id/add_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="#id/delete_btn"
android:layout_centerVertical="true"
android:layout_marginRight="0dp"
android:text="Add" />
</RelativeLayout>
I lowered the height to match the text and It is working properly, thanks to talex