How to add icon to tabs - java

I am trying to add an icon to my tabs and it isnt working,
I tried adding
getResources().getDrawable(R.drawable.bodyicon));
and it still isnt working. When I run the application the tab bar just has the text and there is no icon
I outlined where my code is. If someone could figure out why it isnt working that would be great.
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
public class Body extends Activity implements OnTouchListener, OnClickListener {
Button bAbs, bQuad2, bPecs;
TabHost th;
ImageView body;
final Context context = this;
StretchType pop;
// above I am defining all of the buttons and images, etc...
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(
WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
// here I am saying get rid of the nav bar
setContentView(R.layout.body);
th = (TabHost) findViewById(R.id.thbodyview);
bAbs = (Button) findViewById(R.id.bAbss);
bPecs = (Button) findViewById(R.id.bPecss);
bAbs.setOnClickListener(this);
bPecs.setOnClickListener(this);
//*********************below are my tabs*******************************************
th.setup();
TabSpec specs = th.newTabSpec("Front");
specs.setContent(R.id.Front);
specs.setIndicator("Front",getResources().getDrawable(R.drawable.bodyicon));
th.addTab(specs);
specs = th.newTabSpec("tag2");
specs.setContent(R.id.Back);
specs.setIndicator("Back");
th.addTab(specs);
specs = th.newTabSpec("tag3");
specs.setContent(R.id.tab3);
specs.setIndicator("More...");
th.addTab(specs);
}
//***************************Above are my tabs *******************************
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.bAbss:
// below I am creating the alert dialogue
LayoutInflater li = LayoutInflater.from(context);
View promptsView = li.inflate(R.layout.abs, null);
// above I am setting the customview of the alert dialogue
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
alertDialogBuilder.setView(promptsView);
// here I am officially setting the custom layout
// set dialog message
alertDialogBuilder.setTitle("Stretch Type");
// alert dialogue title
// create alert dialog
final AlertDialog alertDialog = alertDialogBuilder.create();
// above is creating the alert dialogue
final Spinner mSpinner = (Spinner) promptsView
.findViewById(R.id.sSType);
// above is initializing the spinner
/*
* dont need this button final Button mButton = (Button) promptsView
* .findViewById(R.id.bSpinclose);
*/
// reference UI elements from my_dialog_layout in similar fashion
mSpinner.setOnItemSelectedListener(new OnSpinnerItemClicked());
// show it
alertDialog.show();
alertDialog.setCanceledOnTouchOutside(false);
break;
}
}
#Override
public boolean onTouch(View arg0, MotionEvent arg1) {
// TODO Auto-generated method stub
return false;
}
public class OnSpinnerItemClicked implements OnItemSelectedListener {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,
long id) {
switch (pos) {
case (1):
Intent i = new Intent(Body.this, Practice.class);
Body.this.startActivity(i);
break;
}
}
#Override
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
}
}
Here is the xml
<TabHost
android:id="#+id/thbodyview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<TabWidget
android:id="#android:id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true" >
</TabWidget>
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:id="#+id/Front"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:id="#+id/llbottomtop"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:orientation="vertical" >
<TextView
android:id="#+id/tvupper"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/bAbs"
android:text="Upper"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#FFFFFF" />
<View
android:layout_width="match_parent"
android:layout_height="5dp"
android:layout_centerVertical="true"
android:background="#color/orange" />
<TextView
android:id="#+id/tvlower"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/linearLayout1"
android:text="Lower"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#FFFFFF" />
</LinearLayout>
<ImageView
android:id="#+id/ivBody"
android:layout_width="210dp"
android:layout_height="430dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:src="#drawable/body_front" />
<Button
android:id="#+id/bPecss"
android:layout_width="83dp"
android:layout_height="50dp"
android:layout_above="#+id/bAbss"
android:layout_alignRight="#+id/bAbss"
android:text="Pecs" />
<Button
android:id="#+id/bAbss"
android:layout_width="80dp"
android:layout_height="77dp"
android:layout_alignBottom="#+id/llbottomtop"
android:layout_centerHorizontal="true"
android:layout_marginBottom="42dp"
android:text="Abs" />
</RelativeLayout>
</LinearLayout>
<LinearLayout
android:id="#+id/Back"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:id="#+id/llbottomtop"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:orientation="vertical" >
<TextView
android:id="#+id/tvupper"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/bAbs"
android:text="Upper"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#FFFFFF" />
<View
android:layout_width="match_parent"
android:layout_height="5dp"
android:layout_centerVertical="true"
android:background="#color/orange" />
<TextView
android:id="#+id/tvlower"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/linearLayout1"
android:text="Lower"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#FFFFFF" />
</LinearLayout>
<ImageView
android:id="#+id/ivBody"
android:layout_width="210dp"
android:layout_height="430dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:src="#drawable/body_back" />
</RelativeLayout>
</LinearLayout>
<LinearLayout
android:id="#+id/tab3"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</LinearLayout>
</FrameLayout>
</RelativeLayout>
</TabHost>

My tip is to get access to the tab title textview and set left|top|right|bottom drawable
Example:
//to get first tab title as textView from tabHost
TextView tabTitle = (TextView) tabHost.getTabWidget().getChildAt(0)
.findViewById(android.R.id.title);
//to set the icon to left of the tab title
tabTitle.setCompoundDrawablesWithIntrinsicBounds(
getActivity().getResources().getDrawable(
R.drawable.ic_tab_icon), null, null, null);

I have two physical devices one 2.2 and the other 4.2.2. on 2.2 there is no issue and the icon appears. on 4.2.2 there is no icon. Somethings changed in how tabs are laid out in Android. If you really required to use a TabHost i saw you can pass in a view as the tabindicator. This code is kinda pseudo code as it still some adjustment in the UI in terms of layout but try this:
define a layout called tabindicator_layout.xml and put it in res/layout. the contents of which look like this:
<?xml version="1.0" encoding="utf-8"?>
<ImageView
android:id="#+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|top"
android:scaleType="center" >
</ImageView>
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal" />
then in your class code at runtime inflate this view and populate the image and textview with what you desire. do this for each tab:
//*********************below are my tabs*******************************************
th.setup();
TabSpec specs = th.newTabSpec("Front");
specs.setContent(R.id.Front);
View tabIndicator = LayoutInflater.from(this).inflate(
R.layout.tabindicator_layout, th.getTabWidget(), false);
((TextView) tabIndicator.findViewById(R.id.title)).setText("Front");
((ImageView) tabIndicator.findViewById(R.id.image))
.setImageResource(R.drawable.ic_launcher);
specs.setIndicator(tabIndicator);
TabSpec specs2 = th.newTabSpec("tag2");
specs2.setContent(R.id.Back);
View tabIndicator2 = LayoutInflater.from(this).inflate(
R.layout.tabindicator_layout, th.getTabWidget(), false);
((TextView) tabIndicator2.findViewById(R.id.title)).setText("Back");
((ImageView) tabIndicator2.findViewById(R.id.image))
.setImageResource(R.drawable.ic_launcher);
specs2.setIndicator(tabIndicator2);
TabSpec specs3 = th.newTabSpec("tag3");
specs3.setContent(R.id.tab3);
View tabIndicator3 = LayoutInflater.from(this).inflate(
R.layout.tabindicator_layout, th.getTabWidget(), false);
((TextView) tabIndicator3.findViewById(R.id.title)).setText("...More");
((ImageView) tabIndicator3.findViewById(R.id.image))
.setImageResource(R.drawable.ic_launcher);
specs3.setIndicator(tabIndicator3);
th.addTab(specs);
th.addTab(specs2);
th.addTab(specs3);
of course replace R.drawable.ic_launcher with whatever icon you want to show
another interesting thing that might help..i notice if i pass in a blank for the title that the original way works but shows no title. So you could go into photoshop and just add the title to the image and make it even better looking. Try this way:
TabSpec specs = th.newTabSpec("Front");
specs.setContent(R.id.Front);
specs.setIndicator("",getResources().getDrawable(R.drawable.ic_launcher));
th.addTab(specs);

Related

Add many CardViews with onclick method programmatically

I'm still new to the Android and I want to add a CardView to the activity each time a button is clicked. The CardView has text on it and a background image. I already have the XML file that can add this, but because I want to be able to add more than one, I can't use <include.>. The first image is when the button is clicked once and the second is when the button is clicked 3 times. I already have the onClick for the TextView that says "Click To Add Block" and the XML for the CardView, but I can't make it so that you can add them and change the text in the TextView in each and every one of them. I also can't seem to find a way to programmatically add an onClick listener to the programmatically created CardView. Later down the line, I would also like to be able to delete the CardView from a click of a button too.
Here is the CardView XML file (Before it was inside a Relative Layout)
<androidx.cardview.widget.CardView
android:id="#+id/cardviewClassesBlock1"
android:layout_width="330dp"
android:layout_height="75dp"
android:layout_marginTop="90dp"
android:layout_centerHorizontal="true"
app:cardCornerRadius="10dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/ic_launcher_background">
<TextView
android:id="#+id/textviewClassesBlock1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="3dp"
android:textSize="22sp"
android:fontFamily="#font/amiko_semibold"
android:textColor="#color/white"
android:text="Block A"/>
<ImageView
android:layout_width="60dp"
android:layout_height="6dp"
android:layout_marginStart="10dp"
android:layout_below="#+id/textviewClassesBlock1"
android:background="#drawable/rounded_corner_edittext" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_marginEnd="5dp"
android:textColor="#color/white"
android:text="P - 0 | T - 0 | A - 0"/>
</RelativeLayout>
</androidx.cardview.widget.CardView>
I have created a sample project for You.
First You have to create a layout for Your CardView. In res/layout create card_base.xml. In this layout add:
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/cardviewClassesBlock1"
android:layout_width="wrap_content"
android:layout_height="75dp"
android:layout_centerHorizontal="true"
app:cardCornerRadius="10dp"
android:layout_margin="10dp"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/ic_launcher_background"
>
<TextView
android:id="#+id/textviewClassesBlock1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="3dp"
android:text="Block A"
android:textSize="22sp"
/>
<ImageView
android:layout_width="60dp"
android:layout_height="6dp"
android:layout_below="#+id/textviewClassesBlock1"
android:layout_marginStart="10dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginEnd="5dp"
android:text="P - 0 | T - 0 | A - 0"
/>
</RelativeLayout>
</androidx.cardview.widget.CardView>
This is basically Your CardView with small changes.
Next, in Your activity_main.xml add this:
<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.LinearLayoutCompat xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity"
>
<Button
android:id="#+id/butAdd"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Add New Card"
/>
<Button
android:id="#+id/butDoSth"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Do something"
/>
<androidx.appcompat.widget.LinearLayoutCompat
android:id="#+id/cards"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<include
android:id="#+id/includedLayoutFirst"
layout="#layout/card_base"
/>
</androidx.appcompat.widget.LinearLayoutCompat>
</androidx.appcompat.widget.LinearLayoutCompat>
This is a starter (very simple) look of Your app. It has one button and one CardView which is already inserted.
Now in Your MainActivity.java paste this:
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.LinearLayoutCompat;
import androidx.cardview.widget.CardView;
public class MainActivity extends AppCompatActivity
{
private int starter = 66; //ASCII code for `B`
LinearLayoutCompat cards;
Button buttonAdd;
Button buttonDoSth;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cards = findViewById(R.id.cards);
buttonAdd = findViewById(R.id.butAdd);
buttonDoSth = findViewById(R.id.butDoSth);
buttonAdd.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
CardView newCard = new CardView(MainActivity.this);
getLayoutInflater().inflate(R.layout.card_base, newCard);
TextView t = newCard.findViewById(R.id.textviewClassesBlock1);
String current = Character.toString((char) starter++);
t.setText("Block " + current);
newCard.setTag(current); //
cards.addView(newCard);
}
});
buttonDoSth.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
findBlockAndDoSomething("B");
}
});
}
private void findBlockAndDoSomething(String name)
{
Log.d("MyTAG", "CLICK");
for (int i = 0; i < cards.getChildCount(); i++)
{
CardView selected = (CardView) cards.getChildAt(i);
if (selected.getTag() != null && selected.getTag().toString().equals(name))
{
// do something. E.g change block name
TextView textViewClassesBlock1 = selected.findViewById(R.id.textviewClassesBlock1);
textViewClassesBlock1.setText("Block XXX");
return;
}
}
}
}
Result (starter code and with adding new CardView):

OnEditorActionListener() working but cant get the text from EditText

I want to get the username from edit text and display it in the second Activity in TextView id-textView2. When I press enter after writing the name and click start button it goes to the second activity but the text is not being displayed . I tried executing other actions like startActivity() inside onEditorAction method it works after i press enter, but this code is not working
String name = nameText.getText().toString();
Intent p1 = new Intent(MainActivity.this, qPage1.class);
p1.putExtra("user_name",name);
Is it because i declared two times intent, inside onEditorAction() and inside starQuizz method in Activity A. i did this because of scope issues.
Activity A
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.content.Intent;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import android.view.KeyEvent;
import android.widget.TextView.OnEditorActionListener;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText nameText = findViewById(R.id.nameText);
nameText.setOnEditorActionListener(new OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView nameText, int actionId, KeyEvent event) {
boolean handled = false;
if (actionId == EditorInfo.IME_ACTION_SEND || event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
String name = nameText.getText().toString();
Intent p1 = new Intent(MainActivity.this, qPage1.class);
p1.putExtra("user_name",name);
handled = true;
}
return handled;
}
});
}
//OnClick of a Start button
public void startQuizz(View view){
Intent p1 = new Intent(this, qPage1.class);
startActivity(p1);
}
}
Activity A xml layout
<?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:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/beautifulcolorgradientsbackgrounds091eternalconstance"
tools:context=".MainActivity">
<EditText
android:id="#+id/nameText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="181dp"
android:width="300dp"
android:hint="#string/name_input"
android:inputType="text"
android:imeOptions="actionSend"
android:imeActionId="10"/>
<Button
android:id="#+id/start_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="182dp"
android:onClick="startQuizz"
android:text="START" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="45dp"
android:fontFamily="#font/changa_one"
android:text="Are you up for the challenge?"
android:textAlignment="center"
android:textAllCaps="false"
android:textSize="30sp" />
</RelativeLayout>
Activity 2
package com.guesstasif.guesswhat;
import android.content.Intent;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.view.View;
import android.widget.TextView;
public class qPage1 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_q_page1);
final ProgressBar p1progress = findViewById(R.id.pg1progressBar);
Runnable r = new Runnable() {
#Override
public void run() {
int progressStatus = 0;
while (progressStatus<200){
p1progress.incrementProgressBy(1);
android.os.SystemClock.sleep(50);
progressStatus++;
}
RadioButton q1radiobutton3 = findViewById(R.id.q1radioButton3);
RadioButton q2radiobutton1 = findViewById(R.id.q2radioButton1);
Intent p2 = new Intent(qPage1.this, qPage2.class);
//name==============================================================
String name = getIntent().getStringExtra("user_name");
TextView textView2= findViewById(R.id.textView2);
textView2.setText(name);
//==================================================================
if(q1radiobutton3.isChecked() && q2radiobutton1.isChecked())
{
p2.putExtra("intVariableName", 2);
}
else if (q1radiobutton3.isChecked() || q2radiobutton1.isChecked())
{
p2.putExtra("intVariableName", 1);
}
startActivity(p2);
}
};
Thread progressThread =new Thread(r);
progressThread.start();
}
}
Activity 2 xml layout
<?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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".qPage1">
<TextView
android:id="#+id/q1textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:text="Q1.What is the name of the 7th planet of ou Solar system?"
android:textAlignment="center"
android:textSize="24sp" />
<RadioGroup
android:id="#+id/q1radioGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/q1textView"
android:layout_centerHorizontal="true"
android:orientation="horizontal">
<RadioButton
android:id="#+id/q1radioButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Jupiter" />
<RadioButton
android:id="#+id/q1radioButton2"
android:layout_width="84dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Saturn" />
<RadioButton
android:id="#+id/q1radioButton3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Uranus" />
<RadioButton
android:id="#+id/q1radioButton4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Neptune" />
</RadioGroup>
//second Question//
<TextView
android:id="#+id/q2textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginTop="173dp"
android:text="Q2.What is the name of the largest tree in the world?"
android:textAlignment="center"
android:textSize="24sp" />
<RadioGroup
android:id="#+id/q2radioGroup"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_alignParentStart="true"
android:layout_below="#+id/q2textView">
<RadioButton
android:id="#+id/q2radioButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="General Sherman" />
<RadioButton
android:id="#+id/q2radioButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Sequoia sempervirens" />
<RadioButton
android:id="#+id/q2radioButton3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Centurion" />
<RadioButton
android:id="#+id/q2radioButton4"
android:layout_width="wrap_content"
android:layout_height="35dp"
android:layout_weight="1"
android:text="Coast redwood" />
</RadioGroup>
<ProgressBar
android:id="#+id/pg1progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="33dp"
android:max="200" />
<TextView
android:id="#+id/scoreView"
android:layout_width="170dp"
android:layout_height="41dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="89dp" />
<TextView
android:id="#+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="137dp"
android:textAlignment="center" />
</RelativeLayout>
The reason is you start a new Intent in here:
public void startQuizz(View view){
Intent p1 = new Intent(this, qPage1.class);
startActivity(p1);
}
Which does not pass the string and just starts a new Intent-Activity.
Also here:
Intent p1 = new Intent(MainActivity.this, qPage1.class);
p1.putExtra("user_name",name);
You missed to start Intent so:
Intent p1 = new Intent(MainActivity.this, qPage1.class);
p1.putExtra("user_name",name);
startActivity(p1);
And in the quiz method, start another Intent:
Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);
And finally, in the second Activity:
Bundle bundle = getIntent().getExtras();
String name = bundle.getString("user_name");
Also, you were using Thread instead of runOnUIThread(); and that might cause some UI effects.
Look at the startQuizz method - seems like you are not setting the name as an extra to the intent!
You should use a single function that starts the next activity both in the editor action and the button click listener.
It seems you are setting text of a TextView in a background thread.
The UI cannot be altered in a background thread.
Try wrapping the setText() part in runOnUiThread().
Check this out: How do we use runOnUiThread in Android?
I'll answer the most obvious question here. It seems there's a lot of code work being done, here also.
EditText edittext = (EditText) findViewById(R.id.something);
You must, and I cannot stress this enough, as of Level 30, still, you have to cast it as an EditText. In fact, you have to with everything, essentially. Java doesn't like structural propagating without being handed the stalk, not the beans (seeds). So, please one last thing:
String string = edittext.getText().toString()
That works every time in this combination!

Trying to add new TextView to Bottom of Screen and have them Stacked

So currently I have an EditText field and a button and I want every time when that button is pushed to add the name at the bottom of the screen, but continuing to add them to the bottom of the screen rather than one line. It's currently only printing on one line and I don't know how to make the font bigger on the text that is being added. Sorry for the dumb question. This is what I have in the main file and the XML bc it wouldn't let me post right below it
package com.example.bryce.
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.util.Log;
import android.view.View;
import android.content.
public class MainActivity extends
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final LinearLayout mLayout=findViewById(R.id.linearLayout);
final EditText mEditText=findViewById(R.id.StudentNameEdt);
final Button mButton=findViewById(R.id.insertButton);
TextView textView=new TextView(this);
textView.setText("New TExt");
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mLayout.addView(createNewTextView(mEditText.getText().toString()));
}
});
}
private TextView createNewTextView(String text)
{
final LinearLayout mLayout=findViewById(R.id.linearLayout);
String newLine=System.getProperty("line.separator");
final LinearLayout.LayoutParams lparams =new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
RelativeLayout.LayoutParams params= (RelativeLayout.LayoutParams) mLayout.getLayoutParams();
final TextView textView=new TextView(this);
textView.setLayoutParams(lparams);
textView.setText("New texT:: "+text+newLine);
return textView;
}
}
And here is the XML
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/ScrollView01"
android:layout_width="match_parent"
android:layout_height="match_parent">
<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:layout_width="match_parent"
android:layout_height="900dp"
tools:context=".MainActivity">
<TextView
android:id="#+id/NewClassTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="Welcome!"
android:textSize="30sp"
android:textStyle="bold"
android:typeface="serif"
app:fontFamily="sans-serif-smallcaps" />
<TextView
android:id="#+id/WelcomeAgain"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_below="#+id/NewClassTitle"
android:text="Fill out the Form Below to Register"
android:textSize="20sp"
android:textStyle="bold"
android:typeface="serif"
app:fontFamily="sans-serif-smallcaps" />
<EditText
android:id="#+id/ClassNumEdt"
android:layout_width="324dp"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="222dp"
android:ems="10"
android:inputType="textPersonName"
android:text="Class
<Button
android:id="#+id/insertButton"
android:layout_width="wrap_content"
android:layout_height="38dp"
android:layout_above="#+id/StudentView"
android:layout_toStartOf="#+id/NewClassTitle"
android:text="Insert"
android:textSize="14sp" />
<EditText
android:id="#+id/StudentNameEdt"
android:layout_width="337dp"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="295dp"
android:ems="10"
android:inputType="textPersonName"
android:text="Student Name" />
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="0dp"
android:orientation="horizontal"></LinearLayout>
</RelativeLayout>
</ScrollView>
Your LinearLayout orientation appears to be horizontal. It should be vertical where you to expect the lines to be added below.
That being said, consider using a RecyclerView for the task.

Android app crashes with button click

I'm creating a simple quiz according to this tutorial, but the app crashes with the button "Next answer" which is related to a checked radio button.
Main code:
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
public class Display extends Activity {
TextView tv;
Button btnNext;
RadioGroup rg;
RadioButton rb1, rb2,rb3;
String questions[]={"Capital of Portugal?", "Capital of Spain?", "Capital of France?"};
String answers[]={"Lisbn","Madrid","Paris"};
String options[]={"Zuriq", "London","Lisbon","Manchester","Buenos Aires","Madrid", "NY", "Paris","Moscow"};
int flag=0;
public static int marks,correct,wrong;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dispaly);
tv=(TextView) findViewById(R.id.tvque);
btnNext=(Button) findViewById(R.id.btnNext);
rb1= (RadioButton) findViewById(R.id.radioButton);
rb2= (RadioButton) findViewById(R.id.radioButton2);
rb3= (RadioButton) findViewById(R.id.radioButton3);
tv.setText(questions[flag]);
rb1.setText(options[flag*3]);
rb2.setText(options[(flag*3)+1]);
rb3.setText(options[(flag*3)+2]);
Toast.makeText(this, "Negative Marks: " + MainActivity.tbflag, 1000).show();
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//The error comes from the line bellow, i believe:
RadioButton user_answer= (RadioButton)findViewById(rg.getCheckedRadioButtonId());
String answerText=user_answer.getText().toString();
if(answerText.equalsIgnoreCase(answers[flag])){
correct++;
}else{
wrong++;
flag++;
if(flag<questions.length){
tv.setText(questions[flag]);
rb1.setText(options[flag*3]);
rb2.setText(options[(flag*3)+1]);
rb3.setText(options[(flag*3)+2]);
}
else
{
if(MainActivity.tbflag)
{
marks=correct-wrong;
}
else
{
marks=correct;
}
Intent in =new Intent(getApplicationContext(), ResultActivity.class);
startActivity(in);
}
}
}
});
}
}
Log message:
java.lang.NullPointerException: Attempt to invoke virtual method 'int android.widget.RadioGroup.getCheckedRadioButtonId()' on a null object reference
I don't understand this error, why isn't the method being called? Can someone help?
XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.vtorferreira.anew.MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tvque"
tools:text="Questions" />
<RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/group">
<RadioButton
android:text="RadioButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="32dp"
android:id="#+id/radioButton" />
<RadioButton
android:text="RadioButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/radioButton"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="#+id/radioButton2" />
<RadioButton
android:text="RadioButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/radioButton3"
android:layout_below="#+id/radioButton2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RadioGroup>
<Button
android:text="Next Question"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="60dp"
android:layout_marginStart="60dp"
android:layout_marginBottom="125dp"
android:id="#+id/btnNext" />
</RelativeLayout>
The reason you are getting the first NullPointerException is because you must inflate rg before it is used.
The second NullPointerException is possibly due to the fact that you are pressing the "Next" button with no radio button selected. To prevent this, you can add a null check inside the OnClickListener or select one of the radio buttons by default. To select a radio button by default, add the following to your XML:
<RadioGroup
...
android:checkedButton="#+id/some-radio-button-id">
...
</RadioGroup>
Alternatively, you can set the default checked RadioButton in your Activity:
rg.check(R.id.radioButton)

Linear layout not getting visible OnClickListener

I have two layouts. I want to keep one layout gone when the activity is loaded and it should be visible onClick of another layout. so I have added this code OnClickListener of the layout.
additionalContactFrom.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(linearLayoutFrom.getVisibility() == View.GONE){
linearLayoutFrom.setVisibility(View.VISIBLE);
}else{
linearLayoutFrom.setVisibility(View.GONE);
}
}
});
And have set visibility of the layout gone in xml file..
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/LinearLayoutAdditionalContactFrom">
<ImageView
android:layout_width="25dp"
android:layout_height="25dp"
android:id="#+id/imageView13"
android:layout_marginLeft="20dp"
android:background="#drawable/ic_person_black_48dp"
android:layout_marginTop="05dp"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/editText"
android:layout_marginRight="10dp"
android:drawableRight="#drawable/ic_expand_more_black_24dp"
android:text="Additional contact (optional)"
android:cursorVisible="false"
/>
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="60dp"
android:layout_marginRight="50dp"
android:layout_gravity="center"
android:visibility="gone"
android:id="#+id/LinearLayoutFrom">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/editText2"
android:layout_weight="1"
android:hint="Name"
android:layout_gravity="center"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/editText3"
android:layout_weight="1"
android:hint="Phone"
android:layout_gravity="center"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="OR"
android:id="#+id/textView19"
android:layout_gravity="center" />
</LinearLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:id="#+id/textView13"
android:layout_marginLeft="48dp"
android:hint="Input if you're not receiver" />
</LinearLayout>
Unable to understand whats going wrong.. The listener is not getting called at all.. Please help..
Your problem is that your EditText is capturing the click event when you click on it. If you click somewhere else in the LinearLayout it should work.
You can replace the EditText with a TextView if you don't need the user to edit the content.
Change
linearLayoutFrom.setVisibility(View.VISIBLE);
To
findViewById(R.id.YOURLAYOUTID).setVisibility(View.VISIBLE);
I think you can't access to local vars in sub methods
It Seems That Layout Visibility is Already set to GONE, so Onlick listener is not working on hidden View and it should not work too.
INVISBLE means you are trying to add a listener to a view which is not there. You can add the listener to a visible view only.
WORKAROUND
1) Try to make a dummy view which is visible but having the same color as background.
2) Try to set the listener for parent and check the position (whether the position does
belongs to INVISIBLE view).
Please try to set the onClickListener to the EditText and to the ImageView and no to the LinearLayout
The problem is that the Handler of the EditText is most important that the LinearLayout handler.
Almost you can try to make a break point to the OnClick and see what is happend
This is an example to explain you how to do that:
in MainActivity Class:
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;
public class MainActivity extends Activity {
private LinearLayout linearLayoutFrom;
private LinearLayout additionalContactFrom;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
additionalContactFrom = (LinearLayout) findViewById(R.id.LinearLayoutAdditionalContactFrom);
linearLayoutFrom = (LinearLayout) findViewById(R.id.LinearLayoutFrom);
linearLayoutFrom.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),
"linearLayoutFrom clicked!!!", Toast.LENGTH_SHORT)
.show();
if (additionalContactFrom.getVisibility() == View.GONE) {
additionalContactFrom.setVisibility(View.VISIBLE);
} else {
additionalContactFrom.setVisibility(View.GONE);
}
}
});
additionalContactFrom.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),
"additionalContactFrom clicked!!!", Toast.LENGTH_SHORT)
.show();
if (linearLayoutFrom.getVisibility() == View.GONE) {
linearLayoutFrom.setVisibility(View.VISIBLE);
} else {
linearLayoutFrom.setVisibility(View.GONE);
}
}
});
}
}
in xml file:
<FrameLayout 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" >
<LinearLayout
android:id="#+id/LinearLayoutAdditionalContactFrom"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/holo_blue_dark"
android:orientation="horizontal" >
</LinearLayout>
<LinearLayout
android:id="#+id/LinearLayoutFrom"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:layout_marginLeft="60dp"
android:layout_marginRight="50dp"
android:background="#android:color/holo_green_light"
android:orientation="vertical"
android:visibility="gone" >
</LinearLayout>
<TextView
android:id="#+id/textView13"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="48dp"
android:hint="Input if you&apos;re not receiver"
android:textAppearance="?android:attr/textAppearanceSmall" />
</FrameLayout>
This is very important that when you want add some view (for example
add a linearlayout to another linerlayout). you should use framelayout or
relativelayout(do not use linearlayout) for do that.

Categories