Change the whole style of my Android app with Java - java

I'm trying to programatically change the whole style (background color, font and font size) of my app based on which radio button has been checked (cf code below). I have read that for it to work I must write it in the onCreate method, since setTypeFace or setTextSize can't be resolved in other functions.
I also tried to call those two methods in another function, which is called setStyles, but those two methods still can't be resolved and I have no idea why.
I did import android.graphics.Typeface for the font.
Below are my Java code et two of my XML codes.
full Java code :
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout buttonMenu = findViewById(R.id.dynamic_btn);
Button showBtn = new Button(this);
showBtn.setText(R.string.menu);
showBtn.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
showBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
//setStyles(v);
final View myView = getLayoutInflater().inflate(R.layout.style, null);
final AlertDialog.Builder diag = new AlertDialog.Builder(getApplicationContext());
diag.setTitle("Configuration de l'application");
diag.setPositiveButton("Enregistrer", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
RadioGroup radioColGroup = (RadioGroup) ((Dialog)dialog).findViewById(R.id.radioColor);
int col = Color.parseColor("#000000"); // background color
int selectedId = radioColGroup.getCheckedRadioButtonId();
Typeface type = getResources().getFont(R.font.fff_tusj);
if (selectedId == R.id.style1) {
// change background, font and size
col = Color.parseColor("#000000");
type = getResources().getFont(R.font.fff_tusj);
v.setTextSize(40);
}
if (selectedId == R.id.style2) {
// change background, font and size
col = Color.parseColor("#00574A");
type = getResources().getFont(R.font.sansation_light);
v.setTextSize(50);
}
else if (selectedId == R.id.style3) {
// change background, font and size
col = Color.parseColor("#6B0504");
type = getResources().getFont(R.font.oswald_stencil);
v.setTextSize(30);
}
View background = findViewById(R.id.layoutBackground);
background.setBackgroundColor(col);
v.setTypeFace(type);
}
});
diag.setNegativeButton("Annuler", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
});
diag.setView(R.layout.style);
diag.show();
}
});
if(buttonMenu != null) {
buttonMenu.addView(showBtn);
}
}
public void setStyles(View view) {
final View myView = getLayoutInflater().inflate(R.layout.style, null);
final AlertDialog.Builder diag = new AlertDialog.Builder(this);
diag.setTitle("Configuration de l'application");
diag.setPositiveButton("Enregistrer", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
RadioGroup radioColGroup = (RadioGroup) ((Dialog)dialog).findViewById(R.id.radioColor);
int col = Color.parseColor("#000000"); // background color
int selectedId = radioColGroup.getCheckedRadioButtonId();
Typeface type = Typeface.createFromAsset(getAssets(), "fff_tusj.ttf");
if (selectedId == R.id.style1) {
// change background, font and size
col = Color.parseColor("#000000");
type = Typeface.createFromAsset(getAssets(), "oswald_stencil.ttf");
//myView.setTextSize();
}
if (selectedId == R.id.style2) {
// change background, font and size
col = Color.parseColor("#00574A");
type = Typeface.createFromAsset(getAssets(), "sansation_light.ttf");
}
else if (selectedId == R.id.style3) {
// change background, font and size
col = Color.parseColor("#6B0504");
}
View background = findViewById(R.id.layoutBackground);
background.setBackgroundColor(col);
//myView.setTypeFace(type);
}
});
diag.setNegativeButton("Annuler", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
});
diag.setView(R.layout.style);
diag.show();
}
}
activity_main.xml:
<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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical"
android:id="#+id/layoutBackground">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/dynamic_btn"
android:layout_weight="1"/>
<EditText
android:id="#+id/saisie_recherche"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="5"
android:inputType="text"/>
<Button
android:id="#+id/recherche"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/recherche"/>
</LinearLayout>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/resultats"/>
<!-- dynamic menu -->
</LinearLayout>
style.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:id="#+id/style">
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/radioColor"
android:orientation="horizontal"
android:layout_margin="50px"
android:gravity="center">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/style1"
android:text="style 1"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/style2"
android:text="style 2"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/style3"
android:text="style 3"/>
</RadioGroup>
</LinearLayout>

If someone is interested in the answer, I actually changed how I do things.
To change fonts, font sizes and background color I created new themes in the layout file style.xml and declared three new themes.
Then according to the Radio button that was clicked on (if condition), I used the setTheme(nameOfTheme).
It works.

Related

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.

Dialog width and height issue

i use custom dialog but in mobile device and in tab view but design is change when i check on tab
i want same same dialog in all device.
See my below code.
private void startDialog() {
final Dialog dialog = new Dialog(activity);
int width = (int)(getResources().getDisplayMetrics().widthPixels*0.70);
int height = (int)(getResources().getDisplayMetrics().heightPixels*0.65);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.setContentView(R.layout.checkout_alert_dialog);
dialog.show();
dialog.getWindow().setLayout(width, height);
btn_cancle = dialog.findViewById(R.id.btn_cancle);
btn_cancle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(activity, "Cancel coming soon", Toast.LENGTH_LONG).show();
dialog.dismiss();
}
});
btn_continue = dialog.findViewById(R.id.btn_continue);
btn_continue.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(activity, " Ok coming soon", Toast.LENGTH_LONG).show();
dialog.dismiss();
}
});
}
Below is Dialog.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#color/white"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<ImageView
android:id="#+id/iv_pointBox"
android:layout_width="#dimen/_80sdp"
android:layout_height="#dimen/_80sdp"
android:src="#drawable/ic_chekout_popup"
android:layout_centerHorizontal="true"
android:layout_marginTop="#dimen/_30sdp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="#dimen/normal_input_text_size"
android:text="You've chosen to redeem 865 Points and pay 44.44 AED. The Payment process might take Some times, please do not hit the back button or close the app. Would you like to continue. "
android:layout_centerHorizontal="true"
android:layout_marginLeft="#dimen/_20sdp"
android:layout_marginRight="#dimen/_20sdp"
android:layout_below="#+id/iv_pointBox"
android:layout_marginTop="#dimen/_15sdp"
/>
<View
android:layout_width="match_parent"
android:layout_height="#dimen/_1sdp"
android:background="#color/view_color"
android:layout_above="#+id/linerbutton"
/>
<LinearLayout
android:id="#+id/linerbutton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_alignParentBottom="true"
>
<Button
android:id="#+id/btn_cancle"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/lable_cancel"
android:textColor="#color/black"
android:textSize="#dimen/normal_input_text_size"
android:textStyle="bold"
android:background="#null"
android:gravity="center"
android:layout_weight="1"
/>
<View
android:layout_width="#dimen/_1sdp"
android:layout_height="#dimen/_45sdp"
android:background="#color/view_color"
/>
<Button
android:id="#+id/btn_continue"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/lable_continue"
android:textColor="#color/black"
android:textSize="#dimen/normal_input_text_size"
android:textStyle="bold"
android:background="#null"
android:layout_weight="1"
android:gravity="center"
/>
</LinearLayout>
</RelativeLayout>
</LinearLayout>
</LinearLayout>
I mention 2 screenshot of my device :
Mobile Device Screen shot:
Tab Screenshot :
See in screenshot dialog was change. So how to i fix it
Thanks in Advance :
Just look at your layout.xml Your layout height and width is match_parent then it's create a spaces.
Just replace your xml with my xml.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="#dimen/_250sdp"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#color/white"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<ImageView
android:id="#+id/iv_pointBox"
android:layout_width="#dimen/_80sdp"
android:layout_height="#dimen/_80sdp"
android:src="#drawable/ic_chekout_popup"
android:layout_gravity="center_horizontal"
android:layout_marginTop="#dimen/_30sdp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="#dimen/normal_input_text_size"
android:text="You've chosen to redeem 865 Points and pay 44.44 AED. The Payment process might take Some times, please do not hit the back button or close the app. Would you like to continue. "
android:layout_centerHorizontal="true"
android:layout_marginLeft="#dimen/_20sdp"
android:layout_marginRight="#dimen/_20sdp"
android:layout_below="#+id/iv_pointBox"
android:layout_marginTop="#dimen/_15sdp"
/>
<View
android:layout_width="match_parent"
android:layout_height="#dimen/_1sdp"
android:background="#color/view_color"
android:layout_marginTop="#dimen/_50sdp"
/>
<LinearLayout
android:id="#+id/linerbutton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<Button
android:id="#+id/btn_cancle"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/lable_cancel"
android:textColor="#color/black"
android:textSize="#dimen/normal_input_text_size"
android:textStyle="bold"
android:background="#null"
android:gravity="center"
android:layout_weight="1"
/>
<View
android:layout_width="#dimen/_1sdp"
android:layout_height="#dimen/_45sdp"
android:background="#color/view_color"
/>
<Button
android:id="#+id/btn_continue"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/lable_continue"
android:textColor="#color/black"
android:textSize="#dimen/normal_input_text_size"
android:textStyle="bold"
android:background="#null"
android:layout_weight="1"
android:gravity="center"
/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
</LinearLayout>
And remove below three lines in java file No need to change height and width at run time:
int width = (int)(getResources().getDisplayMetrics().widthPixels*0.70);
int height = (int)(getResources().getDisplayMetrics().heightPixels*0.65);
dialog.getWindow().setLayout(width, height);
try custom layout
custom.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ImageView
android:id="#+id/imageDialog"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="6dp" />
<TextView
android:id="#+id/textDialog"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#FFF"
android:layout_toRightOf="#+id/imageDialog"/>
<Button
android:id="#+id/declineButton"
android:layout_width="100px"
android:layout_height="wrap_content"
android:text=" Submit "
android:layout_marginTop="5dp"
android:layout_marginRight="5dp"
android:layout_below="#+id/textDialog"
android:layout_toRightOf="#+id/imageDialog"
/>
</RelativeLayout>
in java file
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.custom);
dialog.setTitle("Title");
to open dialog use
dialog.show();
to dismiss dialog use
dialog.dismiss();
Personally, I prefer to create DialogFragment and set width and height like that:
#Override
public void onResume() {
super.onResume();
Window window = getDialog().getWindow();
int width = getArguments().getInt(BUNDLE_KEY_WIDTH);
int height = getArguments().getInt(BUNDLE_KEY_HEIGHT);
window.setLayout(width, height);
}
Replace the
myAlertDialog.show();
by
alertDialog.show();
and then
alertDialog.getWindow().setLayout(width,height);
it will work perfectly
complete code:
private void startDialog() {
AlertDialog.Builder myAlertDialog = new AlertDialog.Builder(this);
myAlertDialog.setTitle("title");
myAlertDialog.setMessage("use this");
AlertDialog alertDialog = myAlertDialog.create();
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int width = (int) ((int)displaymetrics.widthPixels * 0.9);
int height = (int) ((int)displaymetrics.heightPixels * 0.7);
myAlertDialog.setPositiveButton("Gallery", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
Intent pictureActionIntent = null;
pictureActionIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pictureActionIntent, GALLERY_PICTURE);
}
});
myAlertDialog.setNegativeButton("Camera", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 15);
}
});
alertDialog.show();
alertDialog.getWindow().setLayout(width,height);
}
if still not working then you can use like this:
class DialogView extends DialogFragment {
Context context;
public static DialogView newInstance() {
DialogView f = new DialogView();
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(DialogFragment.STYLE_NO_TITLE, android.R.style.Theme);
context = this.getActivity();
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new Dialog(getActivity(), getTheme()) {
#Override
public void onBackPressed() {
//do your stuff
}
};
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.button_layout_view, container, false);
setCancelable(false);
// RelativeLayout closeBtn = (RelativeLayout) view.findViewById(R.id.bottom_separator); get button ids like this- gallery camera etc and you can use click listener on that
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
int width = (int) (metrics.widthPixels * 0.90);
int height = (int) (metrics.heightPixels * 0.95);
this.getDialog().getWindow().setLayout(width, height);
return view;
}
public static DisplayMetrics getDeviceMetrics(Context context) {
DisplayMetrics metrics = new DisplayMetrics();
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
display.getMetrics(metrics);
return metrics;
}
}
create xml for that with two button and title
button_layout_view
then call like this :
android.support.v4.app.FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
DialogFragment newFragment = DialogView.newInstance();
newFragment.show(ft, "");
Your dialog's width and height is fine in both devices (you are setting them in your startDialog() method).
If you want the ImageView to be smaller in tablet devices, so the proportions are the same in both mobile and tablets, you should use a different dimens file for them:
First, define a dimen for your image:
Inside dimens.xml
<dimen name="dialog_image_size">XXXdp</dimen>
Then, define the same dimen inside /res/values-sw720dp/dimens.xml for 10'' tablets and inside /res/values-sw600dp/dimens.xml for 7'' tablets, and set a smaller dp for them.
Now, when you are on a tablet, a different size will be loaded, so you can use a smaller one to keep the same proportions than in mobile.

Setting OnLongClickListeners to view in listview row intercepts onclick event of listrow

each of my listview's rows holds a number of textviews.
Each textview has singleline set to true and is truncated at the end.
If a textview is truncated, it should be longclickable by the user to open a popup or toast and print the whole text.
So here is my problem:
As soon as I add the OnLongClickListener to a textview, that is part of a row of a listView, the onItemClick method of that listView is not called anymore when the textview is clicked (not longclicked).
XML:
List row item:
<TextView
android:id="#+id/leadingText"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.2"
android:gravity="center"
android:textSize="35sp"
android:singleLine="true"
android:text="20x"/>
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.8"
android:descendantFocusability="blocksDescendants"
android:orientation="vertical">
<ExpandableTextView
android:id="#+id/firstLine"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="25sp"
android:singleLine="true"
android:ellipsize="end"
android:gravity="center_vertical"
android:clickable="false"
android:focusable="false"
/>
<TextView
android:id="#+id/secondLine"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:singleLine="true"
/>
</LinearLayout>
ListView:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ListView
android:id="#+id/list"
android:divider="#android:color/transparent"
android:dividerHeight="5.0dp"
android:layout_width="match_parent"
android:focusable="true"
android:layout_height="match_parent">
</ListView>
</LinearLayout>
Code:
Adding the onItemClickListener to my listView (this happens in a fragment, that holds my listview):
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {
UIListEntry item = (UIListEntry) parent.getItemAtPosition(position);
if(selectedKey != item.getId()) {
selectedKey = item.getId();
view.setSelected(true);
} else {
selectedKey = null;
view.setSelected(false);
view.setActivated(false);
}
}
});
Setting the onLongClickListener in my custom TextView ExpandableTextView
private void init() {
this.post(new Runnable() {
#Override
public void run() {
final ViewTreeObserver vto = getViewTreeObserver();
vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
Layout l = getLayout();
if (l != null) {
int lines = l.getLineCount();
if (lines > 0)
if (l.getEllipsisCount(lines - 1) > 0)
addLongClickListener();
}
vto.removeOnGlobalLayoutListener(this);
}
});
}
});
}
private void addLongClickListener() {
this.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
Toast t = Toast.makeText(SmlApp.getInstance().getApplicationContext(), getText(), Toast.LENGTH_SHORT);
t.show();
return false;
}
});
}
Is there a way to implement an individual onLongClickListener for each textview but keep the onClickListener for the whole row, so the textview does not intercept it and the row is still selectable? Setting the onItemLongClickListener on the listView won't help me, because i don't want the whole row to be longclickable but the individual ExpandableTextView

Set text inside fragment not working after revisiting fragment

I am developing an bus time table android app. I have three fragments.
Inside first fragment I have two radio buttons i.e. From Malegaon & To Malegaon. (Malegaon is name of place).
If I select From Malegaon radio button then I am setting text to sourceEditText as Malegaon. and If I select To Malegaon radio button then I am setting text to destinationEditText as Malegaon.
This condition is working fine, when I visit fragment first time, but if I revisit fragment then From Malegaon radio Button is already selected, sourceEditText is blank and destinationEditText has text as Malegaon.
Here is my snapshot and code for first fragment.
after selecting to Malegaon radio button.
I am just changing visibility of layout. (source edittext,destination edittext,search button is one layout)
OldStandFragment.java
public class OldStandFragment extends Fragment {
public static OldStandFragment fragment ;
private static final String ARG_POSITIONS = "position";
private int positions;
private View myFragmentViewOld;
private LinearLayout fromOldMalegoanView, toOldMalegoanView;
Button selectRouteButton;
public static final String required_dest = "Please Enter Destination";
public static final String required_source = "Please Enter Source";
String language = "";
DbHelper helper;
private String sourceId = "", destinationId = "";
private ArrayList<Route> myArrayList;
private RouteAdapter routeAdapter;
private ListView routeListView;
private EditText sourceEditTextFromMalegoanOld;
private EditText destinationEditTextFromMalegoanOld;
private ImageButton searchFromMalegoanButtonOld;
private EditText sourceEditTextToMalegoanOld;
private EditText destinationEditTextToMalegoanOld;
private ImageButton searchToMalegoanButtonOld;
private RadioButton fromOldMalegoanRadioButton, toOldMalegoanRadioButton;
public OldStandFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
positions = getArguments().getInt(ARG_POSITIONS);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
myFragmentViewOld = inflater.inflate(R.layout.fragment_old_stand, container, false);
selectRouteButton = (Button) myFragmentViewOld.findViewById(R.id.selectRouteButton);
fromOldMalegoanRadioButton = (RadioButton) myFragmentViewOld.findViewById(R.id.fromOldMalegoanRadioButton);
toOldMalegoanRadioButton = (RadioButton) myFragmentViewOld.findViewById(R.id.toOldMalegoanRadioButton);
fromOldMalegoanView = (LinearLayout) myFragmentViewOld.findViewById(R.id.fromOldMalegoanView);
toOldMalegoanView = (LinearLayout) myFragmentViewOld.findViewById(R.id.toOldMalegoanView);
sourceEditTextFromMalegoanOld = (EditText) fromOldMalegoanView.findViewById(R.id.sourceEditText);
destinationEditTextFromMalegoanOld = (EditText) fromOldMalegoanView.findViewById(R.id.destinationEditText);
searchFromMalegoanButtonOld = (ImageButton) fromOldMalegoanView.findViewById(R.id.searchResultButton);
sourceEditTextToMalegoanOld = (EditText) toOldMalegoanView.findViewById(R.id.sourceEditText);
destinationEditTextToMalegoanOld = (EditText) toOldMalegoanView.findViewById(R.id.destinationEditText);
searchToMalegoanButtonOld = (ImageButton) toOldMalegoanView.findViewById(R.id.searchResultButton);
SharedPreferences prefs = getContext().getSharedPreferences("MyPrefsFile", Context.MODE_PRIVATE);
int a = prefs.getInt("LangValue", 0);
if (a == 0) {
language = "English";
} else {
language = "मराठी";
}
helper = new DbHelper(getContext());
fromOldMalegoanRadioButton.setChecked(true);
toOldMalegoanRadioButton.setChecked(false);
fromOldMalegoanView.setVisibility(View.VISIBLE);
toOldMalegoanView.setVisibility(View.GONE);
String stopValue = helper.getStopName("1", language);
sourceEditTextFromMalegoanOld.setText(stopValue);
fromOldMalegoanRadioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (fromOldMalegoanRadioButton.isChecked()) {
toOldMalegoanRadioButton.setChecked(false);
fromOldMalegoanView.setVisibility(View.VISIBLE);
toOldMalegoanView.setVisibility(View.GONE);
helper = new DbHelper(getContext());
String stopValue1 = helper.getStopName("1", language);
sourceEditTextFromMalegoanOld.setText(stopValue1);
destinationEditTextFromMalegoanOld.setText("");
}
}
});
toOldMalegoanRadioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (toOldMalegoanRadioButton.isChecked()) {
fromOldMalegoanRadioButton.setChecked(false);
fromOldMalegoanView.setVisibility(View.GONE);
toOldMalegoanView.setVisibility(View.VISIBLE);
helper = new DbHelper(getContext());
String stopValue2 = helper.getStopName("1", language);
destinationEditTextToMalegoanOld.setText(stopValue2);
sourceEditTextToMalegoanOld.setText("");
}
}
});
searchFromMalegoanButtonOld.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//search result code.
}
});
searchToMalegoanButtonOld.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//search result code.
}
});
return myFragmentViewOld;
}
public static OldStandFragment newInstance(int position) {
if(fragment == null) {
fragment = new OldStandFragment();
}
Bundle bundle = new Bundle();
bundle.putInt(ARG_POSITIONS, position);
fragment.setArguments(bundle);
return fragment;
}
}
fragment_old_stand.xml
<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:orientation="vertical"
android:background="#000000"
android:scrollbars="vertical"
tools:context="com.ashishkudale.malegoanagar.Fragments.OldStandFragment">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Select Direction or Route"
android:gravity="center"
android:textColor="#FFFFFF"
android:id="#+id/Note"
android:textStyle="bold"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_margin="15dp" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RadioGroup
android:id="#+id/rg_ContainerOld"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_marginTop="15dp">
<RadioButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="From Malegaon"
android:id="#+id/fromOldMalegoanRadioButton"
android:layout_marginLeft="5dp"
android:checked="false" />
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp">
<include
android:id="#+id/fromOldMalegoanView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
layout="#layout/source_destination"
android:layout_margin="5dp" />
</LinearLayout>
<RadioButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="To Malegaon"
android:id="#+id/toOldMalegoanRadioButton"
android:layout_marginLeft="5dp" />
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp">
<include
android:id="#+id/toOldMalegoanView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
layout="#layout/source_destination"
android:layout_margin="5dp" />
</LinearLayout>
</RadioGroup>
</LinearLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" Select Route "
android:id="#+id/selectRouteButton"
android:background="#drawable/button_effect"
android:layout_gravity="center_horizontal"
android:layout_margin="5dp" />
</LinearLayout>
</ScrollView>
this is Adapter to call fragment.
MyPagerAdapter
public class MyPagerAdapter extends FragmentPagerAdapter {
private final String[] TITLES = {"Old Stand","New Stand", "Fare"};
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public CharSequence getPageTitle(int position) {
return TITLES[position];
}
#Override
public int getCount() {
return TITLES.length;
}
#Override
public android.support.v4.app.Fragment getItem(int position) {
android.support.v4.app.Fragment fragment = null;
if(position ==0) {
fragment = OldStandFragment.newInstance(position);
}else if(position ==1 ){
fragment = NewStandFragment.newInstance(position);
} else if (position == 2) {
fragment = MapFragment.newInstance(position);
}
return fragment;
}
}
after revisiting OldStandFragment it look like this.
I checked with adding logs everywhere possible. And I found that after revisiting OldStandFragment, toOldMalegoanRadioButton.setOnClickListner() method is getting called.
Now I want to refresh fragment when I re-visit or any other way to solve this issue.
You have to use SharedPreferences to save state of checkbox, try this code
public class StackOne extends AppCompatActivity {
SharedPreferences prefs;
private RadioButton rButton1, rButton2;
private RadioGroup rg_ContainerOld;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.stack_one);
prefs = PreferenceManager.getDefaultSharedPreferences(StackOne.this);
rButton1 = (RadioButton) findViewById(R.id.fromOldMalegoanRadioButton);
rButton2 = (RadioButton) findViewById(R.id.toOldMalegoanRadioButton);
rg_ContainerOld = (RadioGroup) findViewById(R.id.rg_ContainerOld);
GetSelectedRadioButton();
int k = prefs.getInt("rb1", 0);
if (k == 1) {
rButton1.setChecked(true);
sourceEditTextFromMalegoanOld.setText("");
} else if (k == 2) {
rButton2.setChecked(true);
sourceEditTextToMalegoanOld.setText("");
}
}
private void GetSelectedRadioButton() {
rg_ContainerOld.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (group.getCheckedRadioButtonId()) {
case R.id.fromOldMalegoanRadioButton:
prefs.edit().putInt("rb1", 1).commit();
break;
case R.id.toOldMalegoanRadioButton:
prefs.edit().putInt("rb1", 2).commit();
break;
}
}
});
}
}
In your code you are dynamically setting checked state of radiobutton
fromOldMalegoanRadioButton.setChecked(true);
toOldMalegoanRadioButton.setChecked(false);
thats why your radiobutton's oncheckedchanged method will get call. And thats why code in it.

SeekBar null pointer exception

I am using SeekBar to change the opacity level in drawing But I am getting Nullpointer exception in the lines
seekOpq.setMax(100);
and
seekTxt.setText(currLevel);
in the following code..
public void onClick(View view){
if(view.getId()==R.id.opacity_btn){
//launch opacity chooser
final Dialog seekDialog = new Dialog(this);
final TextView seekTxt = (TextView)seekDialog.findViewById(R.id.opq_txt);
final SeekBar seekOpq = (SeekBar)seekDialog.findViewById(R.id.seek);
Toast.makeText(getApplicationContext(),
"start.", Toast.LENGTH_SHORT).show();
seekDialog.setTitle("Opacity level:");
seekDialog.setContentView(R.layout.opacity_chooser);
seekOpq.setMax(100);
int currLevel = drawView.getPaintAlpha();
seekTxt.setText(currLevel);
seekOpq.setProgress(currLevel);
seekOpq.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
seekTxt.setText(Integer.toString(progress)+" % ");
}
#Override
public void onStartTrackingTouch(SeekBar seekBar){}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {}
});
Button opqBtn = (Button)seekDialog.findViewById(R.id.opq_ok);
opqBtn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
drawView.setPaintAlpha(seekOpq.getProgress());
Toast.makeText(getApplicationContext(),
"end.", Toast.LENGTH_SHORT).show();
seekDialog.dismiss();
}
});
}
I have tried giving numeric arguments manualy to these lines like
seekTxt.setText(50);
But the error still remains the same
This is my opacity_chooser.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:gravity="center"
android:orientation="vertical" >
<TextView
android:id="#+id/opq_txt"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:gravity="center"
android:text="100%"
android:textStyle="bold" />
<SeekBar
android:id="#+id/seek"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp" />
<Button
android:id="#+id/opq_ok"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="OK" />
</LinearLayout>
First set Content View after initialize seekbar & textview.
eg.
final Dialog seekDialog = new Dialog(this);
seekDialog.setContentView(R.layout.opacity_chooser);
final TextView seekTxt = (TextView)seekDialog.findViewById(R.id.opq_txt);
final SeekBar seekOpq = (SeekBar)seekDialog.findViewById(R.id.seek);
Toast.makeText(getApplicationContext(),
"start.", Toast.LENGTH_SHORT).show();
seekDialog.setTitle("Opacity level:");
seekOpq.setMax(100);
-------------------

Categories