Programming tabbed activity content - java

Where do I need to put the Java code to program the buttons in a tabbed activity? In the activity that contains those two tabs I have this code:
public class Testes extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
private DatePickerDialog.OnDateSetListener hourSetListener;
private DatePickerDialog.OnDateSetListener dateSetListener;
private Button date_button;
private Button hora_picker;
private TextView date_text;
private TextView hora_text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_testes);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
date_button = (Button) findViewById(R.id.date_button);
date_button.setOnClickListener(
new View.OnClickListener(){
public void onClick(View v){
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
DatePickerDialog date_dialog = new DatePickerDialog(
Testes.this,
android.R.style.Theme_Holo_Light_Dialog_MinWidth,
hourSetListener,
year, month, day);
date_dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
date_dialog.show();
};
}
);
dateSetListener = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker datePicker, int year, int month, int day) {
month=month+1;
date_button.setVisibility(View.GONE);
date_text = (TextView) findViewById(R.id.date_text);
date_text.setVisibility(View.VISIBLE);
String dt = day+"-"+month+"-"+year;
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
try {
sdf.parse(dt);
date_text.setText(dt);
} catch (ParseException e) {
e.printStackTrace();
}
}
};
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_testes, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case go_to_fazer_media:{
if (item.isChecked())
item.setChecked(false);
else{
Intent i = new Intent(Testes.this,Formas.class);
startActivity(i);
return true;
}
}
case definicoes:{
if (item.isChecked())
item.setChecked(false);
else{
return true;
}
}
}
return super.onOptionsItemSelected(item);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch(position){
case 0:
Tab1tests tab1 = new Tab1tests();
return tab1;
case 1:
Tab2calendar tab2 = new Tab2calendar();
return tab2;
default:
return null;
}
}
#Override
public int getCount() {
// Show 3 total pages.
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Adicionar Testes";
case 1:
return "Mapa de Testes";
}
return null;
}
}
These is the xml of the tab that I want to program the buttons:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin">
<TextView
android:id="#+id/section_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/disciplina"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/section_label"
android:layout_margin="20dp"
android:layout_toEndOf="#+id/section_label"
android:text="Disciplina:"
android:textSize="35sp" />
<TextView
android:id="#+id/sala"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/disciplina"
android:layout_margin="20dp"
android:layout_toEndOf="#+id/section_label"
android:text="Sala:"
android:textSize="35sp"/>
<TextView
android:id="#+id/Dia"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/sala"
android:layout_margin="20dp"
android:layout_toEndOf="#+id/section_label"
android:text="Dia:"
android:textSize="35sp" />
<TextView
android:id="#+id/Hora"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/Dia"
android:layout_margin="20dp"
android:layout_toEndOf="#+id/section_label"
android:text="Hora:"
android:textSize="35sp" />
<Button
android:id="#+id/add_test"
style="#style/Widget.AppCompat.Button.Colored"
android:layout_width="wrap_content"
android:layout_height="60dp"
android:layout_marginBottom="95dp"
android:text="Adicionar o teste"
android:textSize="20sp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
<TextView
android:id="#+id/date_text"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_alignStart="#+id/hora_picker"
android:layout_alignTop="#+id/Dia"
android:text="ESCOLHER DATA"
android:textSize="25sp"
android:textStyle="bold"
android:visibility="invisible"/>
<Button
android:id="#+id/date_button"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_alignStart="#+id/hora_picker"
android:layout_alignTop="#+id/Dia"
android:text="ESCOLHER DATA"
android:textSize="25sp"
android:textStyle="bold"
android:onClick="setDate"/>
<TextView
android:id="#+id/hora_text"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:text="ESCOLHER HORA"
android:textStyle="bold"
android:textSize="25sp"
android:layout_alignBottom="#+id/Hora"
android:layout_toEndOf="#+id/Hora"
android:visibility="invisible"/>
<Button
android:id="#+id/hora_button"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:text="ESCOLHER HORA"
android:textStyle="bold"
android:textSize="25sp"
android:layout_alignBaseline="#+id/Hora"
android:layout_toEndOf="#+id/sala" />
<EditText
android:id="#+id/sala_text"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/sala"
android:layout_toEndOf="#+id/Hora"
android:ems="10"
android:hint="NÂȘ/Nome da sala"
android:textSize="25sp"
android:inputType="textPersonName" />
<Spinner
android:id="#+id/spinner2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/disciplina"
android:layout_toEndOf="#+id/disciplina"
android:scrollbarSize="25sp"
android:layout_alignTop="#+id/disciplina" />
}This layout

You will have to code the buttons in the Fragment class which you are using in the activity. In your case you will have to add and code the buttons in the Tab1tests and Tab2calendar classes and not in the activity itself as you have done.

Related

Reading Selected Date without DatePickeView in android studio

I am Parvanshu Sharma and I am a beginner to programming, I am making an application in which
I have done that on button click a date Picker dialog will appear and the button text will be set to the selected by the user, Currently there are 3 buttons for this and I even have a realtime database for uploading this date on Firebase, but now I am having problems in getting the every unique date and uploading it, I am not able to get the selected date.
And as my every stackoverflow question has-
MainActivity.java (Its too big so I haven't shown imports)
public class MainActivity extends AppCompatActivity implements DatePickerDialog.OnDateSetListener, AdapterView.OnItemSelectedListener {
String CurrentDateString;
TextView mainDate;
Integer OrderQuantity = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button SelectDate1 = findViewById(R.id.SelectDateButton1);
Button SelectDate2 = findViewById(R.id.SelectDateButton2);
Button SelectDate3 = findViewById(R.id.SelectDateButton3);
SelectDate1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment datePicker = new DatePickerFragment();
datePicker.show(getSupportFragmentManager(), "Pick item order date");
mainDate = SelectDate1;
}
});
SelectDate2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment datePicker = new DatePickerFragment();
datePicker.show(getSupportFragmentManager(), "Pick item order date");
mainDate = SelectDate2;
}
});
SelectDate3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment datePicker = new DatePickerFragment();
datePicker.show(getSupportFragmentManager(), "Pick item order date");
mainDate = SelectDate3;
}
});
ArrayAdapter<CharSequence> FoodAdapter = ArrayAdapter.createFromResource(this, R.array.FoodList, android.R.layout.simple_spinner_item);
FoodAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner SelectItem1 = findViewById(R.id.SelectItem1);
SelectItem1.setAdapter(FoodAdapter);
SelectItem1.setOnItemSelectedListener(this);
Spinner SelectItem2 = findViewById(R.id.SelectItem2);
SelectItem2.setAdapter(FoodAdapter);
SelectItem2.setOnItemSelectedListener(this);
Spinner SelectItem3 = findViewById(R.id.SelectItem3);
SelectItem3.setAdapter(FoodAdapter);
SelectItem3.setOnItemSelectedListener(this);
ArrayAdapter<CharSequence> QuantityAdapter = ArrayAdapter.createFromResource(this, R.array.Quantity, android.R.layout.simple_spinner_item);
QuantityAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner Quantity1 = findViewById(R.id.SelectQuantity1);
Quantity1.setAdapter(QuantityAdapter);
Quantity1.setOnItemSelectedListener(this);
Spinner Quantity2 = findViewById(R.id.SelectQuantity2);
Quantity2.setAdapter(QuantityAdapter);
Quantity2.setOnItemSelectedListener(this);
Spinner Quantity3 = findViewById(R.id.SelectQuantity3);
Quantity3.setAdapter(QuantityAdapter);
Quantity3.setOnItemSelectedListener(this);
Button DoneButton = findViewById(R.id.DoneButton);
EditText PersonName = findViewById(R.id.PersonName);
EditText PersonPhone = findViewById(R.id.PersonPhone);
EditText PersonAddress = findViewById(R.id.PersonAddress);
FirebaseDatabase database = FirebaseDatabase.getInstance();
DoneButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatabaseReference Name = database.getReference(PersonPhone.getText().toString() + "/Name");
Name.setValue(PersonName.getText().toString());
DatabaseReference Phone = database.getReference(PersonPhone.getText().toString() + "/Phone");
Phone.setValue(PersonPhone.getText().toString());
DatabaseReference Address = database.getReference(PersonPhone.getText().toString() + "/Address");
Address.setValue(PersonAddress.getText().toString());
if (Quantity1.getSelectedItem().toString().equals("0")) {
OrderQuantity -= 1;
}
if (Quantity2.getSelectedItem().toString().equals("0")) {
OrderQuantity -= 1;
}
if (Quantity3.getSelectedItem().toString().equals("0")) {
OrderQuantity -= 1;
}
DatabaseReference OrderQuantities = database.getReference(PersonPhone.getText().toString()+"/OrderQuantity");
OrderQuantities.setValue(OrderQuantity);
if (Quantity1.getSelectedItem().toString() != "0") {
//I want some solution HERE
}
}
});
}
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month);
c.set(Calendar.DAY_OF_MONTH, dayOfMonth);
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
String CurrentDateString = format.format(c.getTime());
mainDate.setText(CurrentDateString);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}```
and here goes my activity_main.xml
```<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/NameTextView"
android:layout_width="93dp"
android:layout_height="wrap_content"
android:layout_marginStart="20sp"
android:layout_marginLeft="20sp"
android:layout_marginTop="10sp"
android:text="Name"
android:textColor="#color/black"
android:textSize="28sp"
android:textStyle="bold" />
<EditText
android:id="#+id/PersonName"
android:layout_width="320dp"
android:layout_height="wrap_content"
android:layout_marginStart="20sp"
android:layout_marginLeft="20sp"
android:ems="10"
android:hint="Name"
android:inputType="textPersonName" />
<TextView
android:id="#+id/PhoneTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20sp"
android:text="Mobile Number"
android:textColor="#color/black"
android:textSize="28sp"
android:textStyle="bold" />
<EditText
android:id="#+id/PersonPhone"
android:layout_width="325dp"
android:layout_height="wrap_content"
android:layout_marginLeft="20sp"
android:ems="10"
android:hint="Mobile number"
android:inputType="phone" />
<TextView
android:id="#+id/AddressTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20sp"
android:text="Address"
android:textColor="#color/black"
android:textSize="28sp"
android:textStyle="bold" />
<EditText
android:id="#+id/PersonAddress"
android:layout_width="328dp"
android:layout_height="wrap_content"
android:layout_marginLeft="20sp"
android:ems="10"
android:hint="Delivery Address"
android:inputType="textPostalAddress" />
<TextView
android:id="#+id/textView4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20sp"
android:text=" Order Details"
android:textColor="#color/black"
android:textSize="20sp"
android:textStyle="bold" />
<TableLayout
android:id="#+id/MainTable"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:stretchColumns="0,1,2"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<TableRow
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_margin="1dp"
android:layout_weight="1"
android:background="#000000"
>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_column="0"
android:layout_margin="1dp"
android:background="#FFFFFF"
android:gravity="center"
android:text=" Date "
android:textAppearance="?android:attr/textAppearanceLarge"
android:textStyle="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_column="1"
android:layout_margin="1dp"
android:background="#FFFFFF"
android:gravity="center"
android:text="Item"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textStyle="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_column="2"
android:layout_margin="1dp"
android:background="#FFFFFF"
android:gravity="center"
android:text="Quantity"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textStyle="bold" />
</TableRow>
<TableRow
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_margin="1dp"
android:layout_weight="1"
android:background="#000000">
<Button
android:id="#+id/SelectDateButton1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Select" />
<Spinner
android:id="#+id/SelectItem1"
android:layout_width="40dp"
android:layout_height="43dp"
android:layout_marginStart="3dp"
android:layout_marginLeft="3dp"
android:layout_marginEnd="2dp"
android:layout_marginRight="2dp"
android:background="#color/white"
android:gravity="center"
android:text="Select Item" />
<Spinner
android:id="#+id/SelectQuantity1"
android:layout_width="40dp"
android:layout_height="43dp"
android:background="#color/white"
android:gravity="center" />
</TableRow>
<TableRow
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_margin="1dp"
android:layout_weight="1"
android:background="#000000">
<Button
android:id="#+id/SelectDateButton2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Select" />
<Spinner
android:id="#+id/SelectItem2"
android:layout_width="40dp"
android:layout_height="43dp"
android:layout_marginStart="3dp"
android:layout_marginLeft="3dp"
android:layout_marginEnd="2dp"
android:layout_marginRight="2dp"
android:background="#color/white"
android:gravity="center"
android:text="Select Item" />
<Spinner
android:id="#+id/SelectQuantity2"
android:layout_width="40dp"
android:layout_height="43dp"
android:background="#color/white"
android:gravity="center" />
</TableRow>
<TableRow
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_margin="1dp"
android:layout_weight="1"
android:background="#000000">
<Button
android:id="#+id/SelectDateButton3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Select" />
<Spinner
android:id="#+id/SelectItem3"
android:layout_width="40dp"
android:layout_height="43dp"
android:layout_marginStart="3dp"
android:layout_marginLeft="3dp"
android:layout_marginEnd="2dp"
android:layout_marginRight="2dp"
android:background="#color/white"
android:gravity="center" />
<Spinner
android:id="#+id/SelectQuantity3"
android:layout_width="40dp"
android:layout_height="43dp"
android:background="#color/white"
android:gravity="center" />
</TableRow>
</TableLayout>
<Button
android:id="#+id/DoneButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Done" />
</LinearLayout>
</ScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>
and I have one more class for creating DatePickerDialog,
the source from where I learnt and implemented that how to make DatePickerDialog is Here
which goes here- (DatePickerFragment.java)
public class DatePickerFragment extends DialogFragment {
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(getActivity(), (DatePickerDialog.OnDateSetListener) getActivity(), year, month, day);
}
}
Tried using an interface. You will have all 3 dates in your main activity, now you can do whatever with them
public class DatePickerFragment extends DialogFragment {
private static applyDate mInterface;
private static int buttonNumberHere;
public interface applyDate {
void setDate(int selectedYear, int selectedMonth, int selectedDay, int buttonNumber);
}
public static DatePickerFragment newInstance(int buttonNumber, applyDate context)
{
DatePickerFragment fragment = new DatePickerFragment();
mInterface = ((applyDate) context);
buttonNumberHere = buttonNumber;
return fragment;
}
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(getContext(), datePickerListener, year, month, day);
}
private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
mInterface.setDate(selectedYear, selectedMonth, selectedDay, buttonNumberHere);
}
};
In MainActivity
public class MainActivity extends AppCompatActivity implements applyDate, AdapterView.OnItemSelectedListener {
String CurrentDateString;
TextView mainDate;// Idk what is this
Integer OrderQuantity = 3;
String itemOneDate;
String itemTwoDate;
String itemThreeDate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button SelectDate1 = findViewById(R.id.SelectDateButton1);
Button SelectDate2 = findViewById(R.id.SelectDateButton2);
Button SelectDate3 = findViewById(R.id.SelectDateButton3);
SelectDate1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatePickerFragment datePicker = DatePickerFragment.newInstance(1, MainActivity.this);
datePicker.show(getSupportFragmentManager(), "Pick item order date");
mainDate = SelectDate1;
}
});
SelectDate2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatePickerFragment datePicker = DatePickerFragment.newInstance(2, MainActivity.this);
datePicker.show(getSupportFragmentManager(), "Pick item order date");
mainDate = SelectDate2;
}
});
SelectDate3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatePickerFragment datePicker = DatePickerFragment.newInstance(3, MainActivity.this);
datePicker.show(getSupportFragmentManager(), "Pick item order date");
mainDate = SelectDate3;
}
});
ArrayAdapter<CharSequence> FoodAdapter = ArrayAdapter.createFromResource(this, R.array.FoodList, android.R.layout.simple_spinner_item);
FoodAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner SelectItem1 = findViewById(R.id.SelectItem1);
SelectItem1.setAdapter(FoodAdapter);
SelectItem1.setOnItemSelectedListener(this);
Spinner SelectItem2 = findViewById(R.id.SelectItem2);
SelectItem2.setAdapter(FoodAdapter);
SelectItem2.setOnItemSelectedListener(this);
Spinner SelectItem3 = findViewById(R.id.SelectItem3);
SelectItem3.setAdapter(FoodAdapter);
SelectItem3.setOnItemSelectedListener(this);
ArrayAdapter<CharSequence> QuantityAdapter = ArrayAdapter.createFromResource(this, R.array.Quantity, android.R.layout.simple_spinner_item);
QuantityAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner Quantity1 = findViewById(R.id.SelectQuantity1);
Quantity1.setAdapter(QuantityAdapter);
Quantity1.setOnItemSelectedListener(this);
Spinner Quantity2 = findViewById(R.id.SelectQuantity2);
Quantity2.setAdapter(QuantityAdapter);
Quantity2.setOnItemSelectedListener(this);
Spinner Quantity3 = findViewById(R.id.SelectQuantity3);
Quantity3.setAdapter(QuantityAdapter);
Quantity3.setOnItemSelectedListener(this);
Button DoneButton = findViewById(R.id.DoneButton);
EditText PersonName = findViewById(R.id.PersonName);
EditText PersonPhone = findViewById(R.id.PersonPhone);
EditText PersonAddress = findViewById(R.id.PersonAddress);
FirebaseDatabase database = FirebaseDatabase.getInstance();
DoneButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Idk how to set date but now you have all three dates
DatabaseReference dateOne = database.getReference(itemOneDate + "/DateOne");
dateOne.setValue(itemOneDate);
DatabaseReference dateTwo = database.getReference(itemOneDate + "/DateTwo");
dateTwo.setValue(itemTwoDate);
DatabaseReference dateThree = database.getReference(itemThreeDate + "/DateThree");
dateThree.setValue(itemThreeDate);
DatabaseReference Name = database.getReference(PersonPhone.getText().toString() + "/Name");
Name.setValue(PersonName.getText().toString());
DatabaseReference Phone = database.getReference(PersonPhone.getText().toString() + "/Phone");
Phone.setValue(PersonPhone.getText().toString());
DatabaseReference Address = database.getReference(PersonPhone.getText().toString() + "/Address");
Address.setValue(PersonAddress.getText().toString());
if (Quantity1.getSelectedItem().toString().equals("0")) {
OrderQuantity -= 1;
}
if (Quantity2.getSelectedItem().toString().equals("0")) {
OrderQuantity -= 1;
}
if (Quantity3.getSelectedItem().toString().equals("0")) {
OrderQuantity -= 1;
}
DatabaseReference OrderQuantities = database.getReference(PersonPhone.getText().toString()+"/OrderQuantity");
OrderQuantities.setValue(OrderQuantity);
if (Quantity1.getSelectedItem().toString() != "0") {
//I want some solution HERE
}
}
});
}
#Override
public void setDate(int selectedYear, int selectedMonth, int selectedDay, int buttonNumber){
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, selectedYear);
c.set(Calendar.MONTH, selectedMonth);
c.set(Calendar.DAY_OF_MONTH, selectedDay);
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
String CurrentDateString = format.format(c.getTime());
mainDate.setText(CurrentDateString);
if (buttonNumber == 1){
itemOneDate = CurrentDateString;
}
else if (buttonNumber == 2){
itemTwoDate = CurrentDateString;
}
else if (buttonNumber == 3){
itemThreeDate = CurrentDateString;
}
}
}

Dynamic Tablerow - inserting a textview contents in an existing tablerow

I'm creating my first android application, and want to use Dynamic Tablerow in my application. In my MainFragment.java, there is OnClickListener for adding text. I use Log.d to check whether it is working or not. I checked it work. But text is not added in Tablerow; its ID is mealRow.
I want add TextView in an existing Tablerow. Please check it and answer to me. Thanks.
I tried new Tablerow. But it also failed.
I mean new TextView in new Tablerow in an existing TableLayout.
MainFragment.java
public static MainFragment newInstance() {
return new MainFragment();
}
#Override
public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.main_fragment, container, false);
Response.Listener<String> responseListener;
responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
String mealList = response;
Log.d(TAG, mealList+"");
//TextView meal = (TextView) getView().findViewById(R.id.meal1);
//meal.setText(mealList);
}
};
Log.d(TAG, "Meal queued!");
MealRequest mealRequest = new MealRequest(countryCode, schulCode, insttNm, schulCrseScCode,
schMmealScCode, schYmd, responseListener);
RequestQueue queue = Volley.newRequestQueue(getActivity());
queue.add(mealRequest);
Button create = (Button) view.findViewById(R.id.Create);
create.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "button Clicked!");
TableRow mealRow = (TableRow) view.findViewById(R.id.mealRow);
ViewGroup.LayoutParams textParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
TextView meals = new TextView(getActivity());
meals.setText("new");
meals.setLayoutParams(textParams);
meals.setGravity(Gravity.CENTER);
meals.setTextColor(Color.parseColor("#000000"));
meals.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
mealRow.addView(meals);
}
});
return view;
}
MainActivity.java
private final static String TAG = MainActivity.class.getName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.fragment_container, MainFragment.newInstance()).commit();
navigationView.setNavigationItemSelectedListener(this);
}
**--------------------------------cut--------------------------**
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_home) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, MainFragment.newInstance()).commit();
} else if (id == R.id.nav_calendar) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, Calendar.newInstance()).commit();
} else if (id == R.id.nav_timetable) {
} else if (id == R.id.nav_homework) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
main_fragment.xml
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Today's meal"
android:textColor="#000000"
android:textSize="20sp"/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TableLayout
android:id="#+id/mealTable"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:stretchColumns="*">
<TableRow
android:id="#+id/mealRow"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/meal1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="1dp"
android:layout_marginBottom="1dp"
android:gravity="center"
android:text="1"
android:textColor="#000000"
android:textSize="20sp" />
<TextView
android:id="#+id/meal2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="1dp"
android:layout_marginBottom="1dp"
android:gravity="center"
android:text="2"
android:textColor="#000000"
android:textSize="20sp" />
<TextView
android:id="#+id/meal3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="1dp"
android:layout_marginBottom="1dp"
android:gravity="center"
android:text="3"
android:textColor="#000000"
android:textSize="20sp" />
<TextView
android:id="#+id/meal4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="1dp"
android:layout_marginBottom="1dp"
android:gravity="center"
android:text="4"
android:textColor="#000000"
android:textSize="20sp" />
</TableRow>
</TableLayout>
</RelativeLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:orientation="horizontal">
<Button
android:id="#+id/Create"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Make Text!" />
</LinearLayout>
This is my expect :
Click 'Create' Button
new TextView is added in mealRow (Tablerow)
but the actual output is 'Nothing happened'.
You should use TableRow.LayoutParams than ViewGroup.LayoutParams.
This is because TextView goes into TableRow.
If TextView goes into RelativeLayout, you should use RelativeLayout.LayoutParams.

Cannot get values from edittext in fragment

I am new over...
My question is: how to obtain the data from the edittext in fragments? I have really tried everything I have been seeking and no result.
Here is the code:
XML Files
register_user.xml
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<include layout="#layout/toolbar"/>
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/secondary_dark"
app:tabMode="fixed"
app:tabGravity="fill"/>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"/>
fragment_pdata.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context="com.fundacioncanihua.inutritionist.rnp.Fragments.PersonalDataFragment">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/pData"
android:layout_marginTop="10dp"
android:textSize="40dp"
android:textStyle="bold"
android:id="#+id/textView"/>
<android.support.design.widget.TextInputLayout
android:id="#+id/flayout_lastname"
android:theme="#style/TextLabel"
android:layout_below="#+id/textView"
android:layout_marginTop="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/input_lName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/lName"
android:inputType="text"
android:maxLength="25"
android:drawableLeft="#drawable/ic_edittext_user"
android:drawablePadding="20dp"/>
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="#+id/flayout_firstname"
android:theme="#style/TextLabel"
android:layout_below="#+id/flayout_lastname"
android:layout_marginTop="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/input_fName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/fName"
android:inputType="text|textCapWords"
android:maxLength="25"
android:drawableLeft="#drawable/ic_edittext_user"
android:drawablePadding="20dp"/>
</android.support.design.widget.TextInputLayout>
<LinearLayout android:layout_width="match_parent"
android:id="#+id/fHorizontal"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_below="#id/flayout_firstname"
android:layout_marginTop="10dp">
<android.support.design.widget.TextInputLayout
android:id="#+id/flayout_birthday"
android:theme="#style/TextLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<EditText
android:id="#+id/input_birthday"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/birthday"
android:inputType="date"
android:drawableLeft="#drawable/ic_edittext_bd"
android:drawablePadding="20dp"/>
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="#+id/flayout_gender"
android:theme="#style/TextLabel"
android:layout_width="150dp"
android:layout_height="wrap_content">
<EditText
android:id="#+id/input_gender"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/gender"
android:inputType="text|textCapSentences"
android:maxLength="1"
android:drawableLeft="#drawable/ic_edittext_gender"
android:drawablePadding="20dp"/>
</android.support.design.widget.TextInputLayout>
</LinearLayout>
<android.support.design.widget.TextInputLayout
android:id="#+id/flayout_location"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/TextLabel"
android:layout_below="#id/fHorizontal"
android:layout_marginTop="10dp">
<EditText
android:id="#+id/input_location"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/location"
android:inputType="text|textCapWords"
android:maxLength="25"
android:drawableLeft="#drawable/ic_edittext_location"
android:drawablePadding="20dp"/>
</android.support.design.widget.TextInputLayout>
Java Classes
Register Patient
public class RegisterPatient extends AppCompatActivity implements PersonalDataFragment.getEditText {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private int[] tabIcons = {
R.drawable.ic_tab_data,
R.drawable.ic_tab_measures,
R.drawable.ic_tab_clinical
};
String s_lname;
private ConnectionSQL dataBase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register_user);
dataBase = new ConnectionSQL(getApplicationContext());
//Setting up the toolbar
Toolbar toolBar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolBar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
setupTabIcons();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.register_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case R.id.action_settings:
//Code
break;
case R.id.regbutton:
registerPatient();
break;
}
return super.onOptionsItemSelected(item);
}
private void setupTabIcons() {
tabLayout.getTabAt(0).setIcon(tabIcons[0]);
tabLayout.getTabAt(1).setIcon(tabIcons[1]);
tabLayout.getTabAt(2).setIcon(tabIcons[2]);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new PersonalDataFragment(), getString(R.string.pData));
adapter.addFragment(new AnthropometryFragment(), getString(R.string.anthro));
adapter.addFragment(new NutritionalClinicalFragment(), getString(R.string.nutcli));
viewPager.setAdapter(adapter);
}
private void registerPatient() {
try {
/*final String s_lName = i_lName.getText().toString();
final String s_fName = i_fName.getText().toString();
final String s_bday = i_bday.getText().toString();
final String s_gender = i_gender.getText().toString();
final String s_location = i_location.getText().toString();
dataBase.addPatient(s_lName, s_fName, s_bday, s_gender, s_location);*/
Toast.makeText(RegisterPatient.this, "Patient added successfully!", Toast.LENGTH_SHORT).show();
clearForm((ViewGroup) findViewById(R.id.registerlayout));
} catch (Exception e) {
Toast.makeText(RegisterPatient.this, "Something were wrong! Try it again.", Toast.LENGTH_SHORT).show();
Log.w("WARNING", e.getMessage());
Log.w("WARNING_INFO", e.getCause());
}
}
private void clearForm(ViewGroup group)
{
for (int i = 0, count = group.getChildCount(); i < count; ++i) {
View view = group.getChildAt(i);
if (view instanceof EditText) {
((EditText)view).setText("");
}
if(view instanceof ViewGroup && (((ViewGroup)view).getChildCount() > 0))
clearForm((ViewGroup)view);
}
}
#Override
public void onFragmentEditTextChanged(String lname) {
}
}
PersonalDataFragment.java
public class PersonalDataFragment extends Fragment{
public EditText editText;
public Calendar myCalendar;
public DatePickerDialog.OnDateSetListener uDate;
private getEditText listener = null;
public PersonalDataFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_pdata, null);
//Calendar
editText = (EditText) v.findViewById(R.id.input_birthday);
final EditText i_lname = (EditText) v.findViewById(R.id.input_lName);
editText.setTextIsSelectable(true);
myCalendar = Calendar.getInstance();
uDate = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
myCalendar.set(Calendar.YEAR, year);
myCalendar.set(Calendar.MONTH, monthOfYear);
myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateLabel();
}
};
editText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View vi) {
// TODO Auto-generated method stub
new DatePickerDialog(getActivity(), uDate, myCalendar
.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
myCalendar.get(Calendar.DAY_OF_MONTH)).show();
}
});
//Getting EditTexts
i_lname.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) { }
#Override
public void afterTextChanged(Editable s) {
if (listener != null) {
final String stg = i_lname.getText().toString();
listener.onFragmentEditTextChanged(stg);
Toast.makeText(getActivity(), stg, Toast.LENGTH_SHORT).show();
}
}
});
return v;
}
#Override
public void onAttach(Context context) {
listener = (getEditText) context;
}
private void updateLabel() {
String myFormat = "dd/MM/yy";
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
editText.setText(sdf.format(myCalendar.getTime()));
}
public interface getEditText {
public void onFragmentEditTextChanged(String lname);
}
}
I don't know what I am doing wrong. I need to get access to those EditText in order to user them and add the user to the SQLite DB but, as the EditText are in the Fragment, I cannot access them directly from the RegisterUser class.
Any ideas on how to solve this? I shall be really and deeply thankful.
Thanks in advance.
Try doing like this,
TextInputLayout FlayoutBirthday= (TextInputLayout) v.findViewById(R.id.flayout_birthday);
EditText i_lname = FlayoutBirthday.getEditText();

How can I make one part of my view scroll together with ListView?

I have two spinners separately, which help me selecting the options and criterias for the ListView to generate, i.e. I need to select a bus and a stop to show the timetable(ListView) which fit the query. Now straight to the problem: I have two spinners in ScrollView and ListView itself. I need to ensure, that it would scroll smoothly when the device is flipped horizontally. All I can is to scroll ListView in fixed height, while it could fill and cover it's whole height, but it's shrinked... Any ideas?
PublicTransport java code:
public class PublicTransport extends Fragment {
private View rootView;
private Spinner routes_spinner, stops_spinner;
private Button submit;
private String spinner_stop_name;
private int bus_id;
private String table_names[] = { "Bus_2", "Bus_2B", "Bus_3", "Bus_4", "Bus_6", "Bus_6B", "Bus_9", "Bus_10", "Bus_11", "Bus_16", "Bus_16B" };
private List<PublicTransportItem> items = new ArrayList<PublicTransportItem>();
private List<String> uniqueStops = new ArrayList<String>();
private CustomPublicTransportListAdapter adapter;
private ListView listView;
private static Locale myLocale;
private Context context;
private EasyTracker easyTracker = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.publictransport, container, false);
context = getActivity().getApplicationContext();
easyTracker = EasyTracker.getInstance(context);
setLanguage();
routes_spinner = (Spinner) rootView.findViewById(R.id.routes_spinner);
ArrayAdapter<CharSequence> routes_adapter = ArrayAdapter.createFromResource(getActivity(),
R.array.routes_array, android.R.layout.simple_spinner_item);
routes_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
routes_spinner.setAdapter(routes_adapter);
stops_spinner = (Spinner) rootView.findViewById(R.id.stops_spinner);
routes_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
bus_id = i;
easyTracker.send(MapBuilder.createEvent("Public_transport",
"Rout", String.valueOf(i), null).build());//Routes i + 1
PublicTransportDatabaseHandler ptdb = new PublicTransportDatabaseHandler(context);
uniqueStops = ptdb.getAllStops(table_names[bus_id]);
ArrayAdapter<String> stops_adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item,
uniqueStops);
stops_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
stops_spinner.setAdapter(stops_adapter);
items = ptdb.getAllPublicTransportItems(table_names[bus_id], spinner_stop_name);
adapter = new CustomPublicTransportListAdapter (context, items, bus_id);
listView = (ListView) rootView.findViewById(R.id.resultsList);
listView.setAdapter(adapter);
listView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
v.getParent().requestDisallowInterceptTouchEvent(true);
break;
case MotionEvent.ACTION_UP:
v.getParent().requestDisallowInterceptTouchEvent(false);
break;
}
v.onTouchEvent(event);
return true;
}
});
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
stops_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
easyTracker.send(MapBuilder.createEvent("Public_transport",
"Stop", String.valueOf(i), null).build());//Stops i + 1
spinner_stop_name = stops_spinner.getItemAtPosition(i).toString();
PublicTransportDatabaseHandler ptdb = new PublicTransportDatabaseHandler(context);
items = ptdb.getAllPublicTransportItems(table_names[bus_id], spinner_stop_name);
adapter = new CustomPublicTransportListAdapter (context, items, bus_id);
listView = (ListView) rootView.findViewById(R.id.resultsList);
listView.setAdapter(adapter);
listView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
v.getParent().requestDisallowInterceptTouchEvent(true);
break;
case MotionEvent.ACTION_UP:
v.getParent().requestDisallowInterceptTouchEvent(false);
break;
}
v.onTouchEvent(event);
return true;
}
});
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
return rootView;
}
public static final PublicTransport newInstance(){
PublicTransport publicTransport = new PublicTransport();
Bundle bdl = new Bundle(2);
publicTransport.setArguments(bdl);
return publicTransport;
}
private void setLanguage() {
SharedPreferences sp = this.getActivity().getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
String lang = sp.getString("languages", "lt");
myLocale = new Locale(lang);
Resources res = getResources();
DisplayMetrics dm = res.getDisplayMetrics();
Configuration conf = res.getConfiguration();
conf.locale = myLocale;
res.updateConfiguration(conf, dm);
}
}
PublicTransport xml code:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:orientation="horizontal"
android:gravity="center_vertical"
android:weightSum="1"
android:layout_marginTop="10dp"
android:background="#drawable/blue_rectangle">
<TextView
android:text="#string/bus_route"
android:layout_height="wrap_content"
android:layout_width="0dip"
android:layout_weight="0.4"
android:textSize="18sp"
android:fontFamily="sans-serif-condensed"
android:textColor="#ffffff" />
<Spinner
android:id="#+id/routes_spinner"
android:layout_height="wrap_content"
android:layout_width="0dip"
android:layout_weight="0.6"
android:entries="#array/routes_array"
android:prompt="#string/route" />
</LinearLayout>
<View
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#ffffff" />
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:orientation="horizontal"
android:gravity="center_vertical"
android:weightSum="1"
android:layout_marginBottom="10dp"
android:background="#drawable/blue_rectangle">
<TextView
android:text="#string/bus_stop"
android:layout_height="wrap_content"
android:layout_width="0dip"
android:layout_weight="0.4"
android:textSize="18sp"
android:fontFamily="sans-serif-condensed"
android:textColor="#ffffff" />
<Spinner
android:id="#+id/stops_spinner"
android:layout_height="wrap_content"
android:layout_width="0dip"
android:layout_weight="0.6"
android:prompt="#string/stop" />
</LinearLayout>
<View
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#ffffff" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/results"
android:padding="8dp"
android:textSize="18dp"
android:textStyle="normal"
android:textColor="#android:color/white"
android:fontFamily="sans-serif-condensed" />
<View
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#ffffff" />
<ListView
android:id="#+id/resultsList"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:divider="#android:color/transparent"
android:dividerHeight="5.0sp">
</ListView>
</LinearLayout>
</ScrollView>
Don't use ListView inside ScrollView...instead, just use ListView and add header view at the top of ListView...
http://developer.android.com/reference/android/widget/ListView.html#addHeaderView(android.view.View)
EDIT:
Here is the example i just created. I hope it helps...

Android - android.view.InflateException: Binary XML file Error inflating class fragment

I am trying to place a fragment in my main activity(ReportFormActivity),which contains a customised listview.I want to inflate a custom layout containing 5 buttons and one spinner into it.I kEEP GETTING THE above error.Following is my complete code.
public class ReportFormActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_report_form);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); //forces the activity to be displayed in landscape mode.
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
public class ButtonRowFragment extends Fragment implements android.view.View.OnClickListener{
Button optionA;
Button optionB;
Button optionC;
Button optionD;
Button optionN;
Spinner interactiveTaskSpinner;
ListView list;
ButtonAdapter adapter;
public ButtonRowFragment CustomListView = null;
public ArrayList<ListModel> CustomListViewValuesArr = new ArrayList<ListModel>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//watch out here
View view= inflater.inflate(R.layout.listview, container, false);
CustomListView = this;
setListData();
Resources res = getResources();
list = (ListView)getView().findViewById(R.id.list);
adapter = new ButtonAdapter(CustomListView, CustomListViewValuesArr,res);
list.setAdapter(adapter);
optionA=(Button)view.findViewById(R.id.button1);
optionB=(Button)view.findViewById(R.id.button2);
optionC=(Button)view.findViewById(R.id.button3);
optionD=(Button)view.findViewById(R.id.button4);
optionN=(Button)view.findViewById(R.id.button5);
optionA.setOnClickListener(this);
optionB.setOnClickListener(this);
optionC.setOnClickListener(this);
optionD.setOnClickListener(this);
optionN.setOnClickListener(this);
interactiveTaskSpinner = (Spinner)view. findViewById(R.id.interactive_task_spinner);
return view;
}
public void setListData() {
for (int i = 0; i < 11; i++) {
final ListModel sched = new ListModel();
/******* Firstly take data in model object ******/
sched.setCompanyName("Button " + i);
sched.setImage("Spinner" + i);
sched.setUrl("http:\\www." + i + ".com");
/******** Take Model Object in ArrayList **********/
CustomListViewValuesArr.add(sched);
}
}
public void onItemClick(int mPosition)
{
ListModel tempValues = ( ListModel ) CustomListViewValuesArr.get(mPosition);
// SHOW ALERT
// Toast.makeText(CustomListView, ""+tempValues.getCompanyName() +" Image:"+tempValues.getImage() +" Url:"+tempValues.getUrl(), Toast.LENGTH_LONG).show();
}
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
switch(view.getId()){
case R.id.button1:
//DO something
optionA.setBackgroundColor(getResources().getColor(R.color.green));
optionC.setBackgroundColor(getResources().getColor(R.color.purple));
optionD.setBackgroundColor(getResources().getColor(R.color.purple));
optionN.setBackgroundColor(getResources().getColor(R.color.purple));
optionB.setBackgroundColor(getResources().getColor(R.color.purple));
break;
case R.id.button2:
//DO something
optionA.setBackgroundColor(getResources().getColor(R.color.purple));
optionC.setBackgroundColor(getResources().getColor(R.color.purple));
optionD.setBackgroundColor(getResources().getColor(R.color.purple));
optionN.setBackgroundColor(getResources().getColor(R.color.purple));
optionB.setBackgroundColor(getResources().getColor(R.color.green));
break;
case R.id.button3:
//DO something
optionA.setBackgroundColor(getResources().getColor(R.color.purple));
optionD.setBackgroundColor(getResources().getColor(R.color.purple));
optionN.setBackgroundColor(getResources().getColor(R.color.purple));
optionB.setBackgroundColor(getResources().getColor(R.color.purple));
optionC.setBackgroundColor(getResources().getColor(R.color.green));
break;
case R.id.button4:
//DO something
optionA.setBackgroundColor(getResources().getColor(R.color.purple));
optionC.setBackgroundColor(getResources().getColor(R.color.purple));
optionN.setBackgroundColor(getResources().getColor(R.color.purple));
optionB.setBackgroundColor(getResources().getColor(R.color.purple));
optionD.setBackgroundColor(getResources().getColor(R.color.green));
break;
case R.id.button5:
//DO something
optionA.setBackgroundColor(getResources().getColor(R.color.purple));
optionC.setBackgroundColor(getResources().getColor(R.color.purple));
optionD.setBackgroundColor(getResources().getColor(R.color.purple));
optionB.setBackgroundColor(getResources().getColor(R.color.purple));
optionN.setBackgroundColor(getResources().getColor(R.color.green));
break;
}
}
}
This is the xml layout for the ReportFormActivity
Below is the layout for listview(meant to be inflated in the listview)
<?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="wrap_content"
android:padding="10dp"
android:orientation="horizontal" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Topic Presentation"
android:textSize="19px" />
<Button
android:id="#+id/button1"
android:layout_width="30dp"
android:layout_height="30dip"
android:background="#color/Purple"
android:text="A"
android:layout_marginLeft="30dp"
android:textColor="#color/white"
android:textSize="15dp"
android:textStyle="bold" />
<Button
android:id="#+id/button2"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_marginLeft="20dp"
android:background="#color/Purple"
android:text="B"
android:textColor="#color/white"
android:textSize="15dp"
android:textStyle="bold" />
<Button
android:id="#+id/button3"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_marginLeft="20dp"
android:background="#color/Purple"
android:text="C"
android:textColor="#color/white"
android:textSize="15dp"
android:textStyle="bold" />
<Button
android:id="#+id/button4"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_marginLeft="20dp"
android:background="#color/Purple"
android:text="D"
android:textColor="#color/white"
android:textSize="15dp"
android:textStyle="bold" />
<Button
android:id="#+id/button5"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_marginLeft="20dp"
android:background="#color/Purple"
android:text="NTP"
android:textColor="#color/white"
android:textSize="15dp"
android:textStyle="bold" />
<Spinner
android:id="#+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="31dp" />
</LinearLayout>

Categories